Python使用可选的key/val对标记句子

2024-05-16 22:50:34 发布

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

我试图分析一个句子(或一行文本),其中你有一个句子,并且可以选择在同一行跟随一些key/val对。键/值对不仅是可选的,而且是动态的。我想要的结果是:

输入:

"There was a cow at home. home=mary cowname=betsy date=10-jan-2013"

输出:

^{pr2}$

输入:

"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新手。我知道这可能是一个正则表达式的解决方案,但我不是最好的正则表达式。


Tags: storehomeissam句子mikelargesmith
3条回答

如果你的句子保证在.结束,那么,你可以按照下面的方法。在

>>> testList = inputString.split('.')
>>> Values['theSentence'] = testList[0]+'.'

对于其余的值,就这么做。在

^{pr2}$

给你一个这样的Values

>>> Values
{'date': '10-jan-2013', 'home': 'mary', 'cowname': 'betsy', 'theSentence': 'There was a cow at home.'}
>>> Values2
{'lastname': 'Smith', 'theSentence': 'Mike ordered a large hamburger.', 'store': 'burgerville'}
>>> Values3
{'theSentence': 'Sam is nice.'}

我会使用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

如果您愿意,这里有更紧凑的版本:

^{pr2}$

或者,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

第一步是做

inputStr = "There was a cow at home. home=mary cowname=betsy date=10-jan-2013"
theSentence, others = str.split('.')

然后你就会想拆散“其他人”。试试split()(传入的参数告诉Python要在什么地方拆分字符串),看看能做些什么。:)

相关问题 更多 >