字符串操作:将平面字符串转换为树状形式

2024-05-18 21:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一棵树:

Active Mode
   |___ Local (EU)
   |       |___ <Random String>
   |___ International (WW)
   |       |___ <Random String> (I want this random string!!!)
Passive Mode
   |___ Local (EU)
   |       |___ <Random String>
   |___ International (WW)
           |___ <Random String>

但由于环境的原因,我的python会将其视为一个扁平字符串:

Active Mode
Local (EU)
<Random String>
International (WW)
<Random String> (I want this random string!!!)
Passive Mode
Local (EU)
<Random String>
International (WW)
<Random String>

注意:基本上是一个随机字符串,我不知道它是什么

现在很容易得到我想要的线路,我只要string.split(\n)[4]。棘手的部分是:

  • 父代(Active ModePassive Mode)可以被洗牌,这样Active Mode将在Passive Mode之后
  • 子级(Local (EU)International (WW))也可以洗牌
  • 一个父母可能失踪或者一个孩子可能失踪(所以有可能没有Active Mode,这意味着我应该得到类似None的东西)

我想到的一个可能的解决方案是以某种方式将扁平字符串转换成多层字典、列表或json,但我不知道该怎么做


Tags: 字符串stringmodelocalrandomthisactivepassive
1条回答
网友
1楼 · 发布于 2024-05-18 21:24:16

我草拟了一些代码,但可能会很危险,因为通常无法保证模式中的随机字符串不会与标题和/或模式名冲突:

def parse(text):
    lines = text.split('\n')
    out = {}
    mode, options = None, None
    for l in filter(None, lines):
        if l.endswith(' Mode'):  # must be really careful here
            out[l] = out.get(l, {})
            mode = out[l]
            options = None
            continue

        # and here...
        if l.startswith('Local (') or l.startswith('International ('):
            mode[l] = mode.get(l, [])
            options = mode[l]
            continue

        options.append(l)

    return out

t = '''
Active Mode
Local (EU)
<Random String>
International (WW)
<Random String> (I want this random string!!!)
Passive Mode
Local (EU)
<Random String>
International (WW)
<Random String>
'''

print(parse(t))

parse()函数的思想是跟踪局部变量modeoptions中的当前模式。同时,它在out中维护一个完整的结果对象

相关问题 更多 >

    热门问题