[英]Picking phrases containing specific words in python
I have a list with 10 names and a list with many of phrases.我有一个包含 10 个名字的列表和一个包含许多短语的列表。 I only want to select the phrases containing one of those names.我只想选择包含这些名称之一的短语。
ArrayNames = [Mark, Alice, Paul]
ArrayPhrases = ["today is sunny", "Paul likes apples", "The cat is alive"]
In the example, is there any way to pick only the second phrase considering the face that contains Paul, given these two arrays?在这个例子中,考虑到包含 Paul 的脸,有没有办法只选择第二个短语,给定这两个数组? This is what I tried:这是我尝试过的:
def foo(x,y):
tmp = []
for phrase in x:
if any(y) in phrase:
tmp.append(phrase)
print(tmp)
x is the array of phrases, y is the array of names. x 是短语数组,y 是名称数组。 This is the output:这是输出:
if any(y) in phrase:
TypeError: coercing to Unicode: need string or buffer, bool found
I'm very unsure about the syntax I used concerning the any() construct.我非常不确定我使用的有关 any() 构造的语法。 Any suggestions?有什么建议?
Your usage of any is incorrect, do the following:您对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)
Output输出
['Paul likes apples']
You are getting a TypeError because any returns a bool and your trying to search for a bool inside a string ( if any(y) in phrase:
).你得到一个TypeError因为 any 返回一个 bool 并且你试图在一个字符串中搜索一个 bool ( if any(y) in phrase:
。
Note that any(y)
works because it will use the truthy value of each of the strings of y
.请注意, any(y)
有效,因为它将使用y
的每个字符串的真值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.