匹配组的单词

时间:2014-08-24 07:09:52

标签: python

我想查找字典中的单词,看看它们是否在我作为输入的文本中。

例如我的词典是:

{ 'excited': 3, 'does not work': -2, 'didnt like': -3,'like' : 3}

我的文字是:

The restaurant was awesome. I was really excited to eat octopus, but i didn't like
shrimps served there. 

问题在于,正如我正在逐字阅读文字一样,它很容易阅读像“兴奋”这样的词。并在字典中找到它,但我如何匹配一组词,例如'不喜欢'?
我的代码如下所示:

text= 'The restaurant was awesome. I was really excited to eat octopus, but i 
didnt like shrimps served there.'
words= text.split()
dict= { 'excited': 3, 'does not work': -2, 'didnt like': -3,'like' : 3}
for word in words:
    if dict.has_key(word):
        print word

1 个答案:

答案 0 :(得分:0)

尝试使用str.count和for循环。

d = {'excited': 3, 'does not work': -2, 'didnt like': -3, 'like' : 3}
result_dict = dict.fromkeys(d, 0)
for word in d.keys()
    result_dict[word] = text.count(word)

更快可能正在使用正则表达式。

d = {'excited': 3, 'does not work': -2, 'didnt like': -3, 'like' : 3}
pat = re.compile("("+"|".join([re.escape(key) for key in sorted(d, key=len, reverse=True)])+")")
results = pat.findall(text)
# ['excited', 'like']