我正在尝试解析一个句子(或文本行),其中您有一个句子,并且可以选择在同一行上跟随一些键/值对。键/值对不仅是可选的,而且是动态的。我正在寻找类似这样的结果:
输入:
"There was a cow at home. home=mary cowname=betsy date=10-jan-2013"
输出:
Values = {'theSentence' : "There was a cow at home.",
'home' : "mary",
'cowname' : "betsy",
'date'= "10-jan-2013"
}
输入:
"Mike ordered a large hamburger. lastname=Smith store=burgerville"
输出:
Values = {'theSentence' : "Mike ordered a large hamburger.",
'lastname' : "Smith",
'store' : "burgerville"
}
输入:
"Sam is nice."
输出:
Values = {'theSentence' : "Sam is nice."}
感谢任何输入/方向。我知道句子出现这是一个家庭作业问题,但我只是一个 python 新手。我知道这可能是一个正则表达式解决方案,但我不是正则表达式方面的最佳人选。
最佳答案
我会使用 re.sub
:
import re
s = "There was a cow at home. home=mary cowname=betsy date=10-jan-2013"
d = {}
def add(m):
d[m.group(1)] = m.group(2)
s = re.sub(r'(\w+)=(\S+)', add, s)
d['theSentence'] = s.strip()
print d
如果您愿意,这里有更紧凑的版本:
d = {}
d['theSentence'] = re.sub(r'(\w+)=(\S+)',
lambda m: d.setdefault(m.group(1), m.group(2)) and '',
s).strip()
或者,也许 findall
是更好的选择:
rx = '(\w+)=(\S+)|(\S.+?)(?=\w+=|$)'
d = {
a or 'theSentence': (b or c).strip()
for a, b, c in re.findall(rx, s)
}
print d
关于带有可选键/值对的 Python tokenize 句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17795174/