给定一个字符串:
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解析器。在
下面是一个使用正则表达式库的方法。我不知道它是不是更有效,或者甚至可以用Python来形容:
在Python2.x中,可以使用}。在
map(float, v.split())
,而不是{与原始程序不同,这个程序允许在
=
和第一个值之间没有空格的地方输入。此外,在key=
的第一个实例之前的输入中的任何项都将被静默忽略。最好是显式地识别它们并抛出一个错误。在图案说明:
^{pr2}$由于输入字符串由空格分隔,并且您要么有键,要么有值,所以可以使用split(),然后循环遍历元素并分配它们。在
我假设字符串的第一个元素总是一个键,所以当
key
是空字符串时,answer[key]
永远不会被调用。在相关问题 更多 >
编程相关推荐