在python中选择包含特定单词的短语

2024-10-01 07:38:47 发布

您现在位置: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()构造的语法。有什么建议吗


Tags: in名称列表ifisany数组名字
1条回答
网友
1楼 · 发布于 2024-10-01 07:38:47

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

您得到了一个TypeError,因为any返回一个bool,您试图在字符串(if any(y) in phrase:)中搜索bool

注意any(y)之所以有效,是因为它将使用y的每个字符串的truthy

相关问题 更多 >