找出段落中出现的单词

2024-05-27

sentence = 'Alice was not a bit hurt, and she jumped up on to her feet in a moment.'
words = ['Alice','jumped','played']

我可以使用filterpython中的函数查找所有元素words显示在sentence:

print filter(lambda x: x in words,sentence.split())

但如果元素中有空格words, .split()函数导致错误:

words = ['Alice','jumped up','played']

在这种情况下,'jumped up'无法在以下位置找到sentence,这是不正确的。

有没有一个简单的方法可以解决这个问题(也许re包可以吗?)


您可以为此使用正则表达式:

In [71]: import re

In [72]: words = ['Alice','jumped','played']

In [73]: [w for w in words if re.search(r'\b{}\b'.format(re.escape(w)), sentence)]
Out[73]: ['Alice', 'jumped']

In [74]: words = ['Alice','jumped up','played']

In [75]: [w for w in words if re.search(r'\b{}\b'.format(re.escape(w)), sentence)]
Out[75]: ['Alice', 'jumped up']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

找出段落中出现的单词 的相关文章

随机推荐