sentence = 'Alice was not a bit hurt, and she jumped up on to her feet in a moment.'
words = ['Alice','jumped','played']
我可以使用filter
python中的函数查找所有元素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(使用前将#替换为@)