【问题标题】:String Manipulation: convert flat string to a tree-like format字符串操作:将扁平字符串转换为树状格式
【发布时间】:2018-09-16 11:40:56
【问题描述】:

我有这棵树:

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

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

【问题讨论】:

  • 你能有你想要的线路而不是国际(WW)线路吗?
  • 我不明白你的意思。如果您问“国际(WW)”线是否是我可以控制的线,那么不是。 “Active Mode”、“Passive Mode”、“International (WW)”和“Local (EU)”是不会改变的预定义变量。然而,他们的顺序或他们的存在可能会有所不同。其他行是一些我不知道的变量。 (希望我说得通)
  • 我在问这样的问题:Active Mode Local (EU) I don't want this line I want this line

标签: python json string tree format


【解决方案1】:

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

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中维护了一个完整的结果对象。

【讨论】:

    猜你喜欢
    • 2019-04-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多