带有可选键/值对的 Python tokenize 句子

标签 python regex tokenize text-parsing

我正在尝试解析一个句子(或文本行),其中您有一个句子,并且可以选择在同一行上跟随一些键/值对。键/值对不仅是可选的,而且是动态的。我正在寻找类似这样的结果:

输入:

"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/

相关文章:

c++ - 是否有 cpp 文件的标记器

swift - osx DDMathParser - 在字符串中查找函数标记

python - for循环中的for循环没有正确执行

Python:更改大写字母

python - 将内部列表的元素相乘作为列表理解

javascript - 正则表达式:读取数字后面的字符

Java正则表达式匹配替换子字符串

python - Python 中 NLTK 的命名实体识别。识别网元

Ruby - 拆分由空格或逗号处的电子邮件组成的字符串

elasticsearch - ElasticSearch:尝试获取专有名称的拼写建议