在文本python3中查找列表中的某个单词

2024-09-27 21:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找方法来查找列表中适合值的所有文本: 例如:

words =['a', 'ball','hello']
# No. of text:   1                2             3                   4
texts= ["i'm need a answer", "Hi daddy", "hello world", "I love to dance ballet"]

预期结果:

  1. 显示:因为“a”这个词
  2. 未显示:虽然有字母“a”,但它并没有作为一个独立的单词出现
  3. 显示:因为“你好”这个词
  4. 未显示:虽然有“ballet”一词,“ball”一词并没有作为一个独立的词出现

我尝试使用循环(从文本中的单词中搜索单词,但没有成功)

非常感谢你的帮助


Tags: of方法notextanswer文本hello列表
3条回答

Python 3:

out = []
for i in texts:
    split = i.split(' ')
    if any((i in split for i in words)):
        out.append(i)

您可以在空白处拆分文本以隔离单词。使用拆分文本和单词的交叉点查找重叠部分。下面的此函数用于筛选具有与声明的词集重叠的词集的文本

def filter_texts(texts):
    words_set = {'a', 'ball', 'hello'}
    filtered = filter(lambda text: set(text.split(' ')) & words_set, texts)
    return list(filtered)

# No. of text:   1                2             3                   4
texts = ["i'm need a answer", "Hi daddy", "hello world", "I love to dance ballet"]
filter_texts(texts)
>> ["i'm need a answer", "hello world"]
words = ['a', 'ball','hello']
texts = ["i'm need a answer", "Hi daddy", "hello world", "I love to dance ballet"]

for txt in texts:
    if any(w in words for w in txt.split()):
        print(w)

相关问题 更多 >

    热门问题