首页 > 解决方案 > 在python中挑选包含特定单词的短语

问题描述

我有一个包含 10 个名称的列表和一个包含许多短语的列表。我只想选择包含其中一个名称的短语。

ArrayNames = [Mark, Alice, Paul]
ArrayPhrases = ["today is sunny", "Paul likes apples", "The cat is alive"]

在示例中,考虑到包含 Paul 的脸,给定这两个数组,有没有办法只选择第二个短语?这是我尝试过的:

def foo(x,y):
tmp = []
for phrase in x:
    if any(y) in phrase:
        tmp.append(phrase)     
print(tmp)

x 是短语数组,y 是名称数组。这是输出:

    if any(y) in phrase:
TypeError: coercing to Unicode: need string or buffer, bool found

我非常不确定我使用的关于 any() 构造的语法。有什么建议么?

标签: pythonif-statementsyntaxany

解决方案


您对any的使用不正确,请执行以下操作:

ArrayNames = ['Mark', 'Alice', 'Paul']
ArrayPhrases = ["today is sunny", "Paul likes apples", "The cat is alive"]

result = []
for phrase in ArrayPhrases:
    if any(name in phrase for name in ArrayNames):
        result.append(phrase)

print(result)

输出

['Paul likes apples']

你得到一个TypeErrorif any(y) in phrase:因为 any 返回一个 bool 并且你试图在一个字符串 ( )中搜索一个 bool 。

请注意,这是any(y)有效的,因为它将使用每个字符串的y值。


推荐阅读