如何用空格分隔的键值对来解析字符串?

2024-09-30 12:29:22 发布

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

给定一个字符串:

LexicalReordering0= -1.88359 0 -1.6864 -2.34184 -3.29584 0 Distortion0= -4 LM0= -85.3898 WordPenalty0= -13 PhrasePenalty0= 11 TranslationModel0= -6.79761 -3.06898 -8.90342 -4.35544

它包含以=结尾的所需字典的键,直到下一个键为止,其余由空格分隔的值都是当前键的值。在

请注意,在解析输入字符串之前不知道键的名称

生成的词典应如下所示:

{'PhrasePenalty0=': [11.0], 'Distortion0=': [-4.0], 'TranslationModel0=': [-6.79761, -3.06898, -8.90342, -4.35544], 'LM0=': [-85.3898], 'WordPenalty0=': [-13.0], 'LexicalReordering0=': [-1.88359, 0.0, -1.6864, -2.34184, -3.29584, 0.0]}

我可以用这个循环:

>>> textin ="LexicalReordering0= -1.88359 0 -1.6864 -2.34184 -3.29584 0 Distortion0= -4 LM0= -85.3898 WordPenalty0= -13 PhrasePenalty0= 11 TranslationModel0= -6.79761 -3.06898 -8.90342 -4.35544"
>>> thiskey = ""
>>> thismap = {}
>>> for element in textin.split():
...     if element[-1] == '=':
...             thiskey = element
...             thismap[thiskey] = []
...     else:
...             thismap[thiskey].append(float(element))
... 
>>> map
{'PhrasePenalty0=': [11.0], 'Distortion0=': [-4.0], 'TranslationModel0=': [-6.79761, -3.06898, -8.90342, -4.35544], 'LM0=': [-85.3898], 'WordPenalty0=': [-13.0], 'LexicalReordering0=': [-1.88359, 0.0, -1.6864, -2.34184, -3.29584, 0.0]}

但是有没有其他方法可以从输入字符串中获得相同的字典?或者一些pyex解析器。在


Tags: 字符串名称字典结尾element空格textinthiskey
2条回答

下面是一个使用正则表达式库的方法。我不知道它是不是更有效,或者甚至可以用Python来形容:

pat = re.compile(r'''([^\s=]+)=\s*((?:[^\s=]+(?:\s|$))*)''')

# The values are lists of strings
entries = dict((k, v.split()) for k, v in pat.findall(textin))

# Alternative if you want the values to be floating point numbers
entries = dict((k, list(map(float, v.split())))
               for k, v in pat.findall(textin))

在Python2.x中,可以使用map(float, v.split()),而不是{}。在

与原始程序不同,这个程序允许在=和第一个值之间没有空格的地方输入。此外,在key=的第一个实例之前的输入中的任何项都将被静默忽略。最好是显式地识别它们并抛出一个错误。在

图案说明:

^{pr2}$

由于输入字符串由空格分隔,并且您要么有键,要么有值,所以可以使用split(),然后循环遍历元素并分配它们。在

entries = textin.split()
key = ""
for x in entries:
    try:
        x = float(x)
        answer[key].append(x)
    except ValueError:
        key = x[:-1] # ignore last char '='
        answer[key] = []

我假设字符串的第一个元素总是一个键,所以当key是空字符串时,answer[key]永远不会被调用。在

相关问题 更多 >

    热门问题