gpt4 book ai didi

python - 找出段落中出现的单词

转载 作者:行者123 更新时间:2023-11-28 21:55:19 24 4
gpt4 key购买 nike

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

我可以使用 python 中的 filter 函数从 sentence 中显示的 words 中找到所有元素:

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']

关于python - 找出段落中出现的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22862151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com