Picking phrases containing specific words in python

IanWing :

I have a list with 10 names and a list with many of phrases. 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? 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. 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 suggestions?

Dani Mesejo :

Your usage of any is incorrect, do the following:

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:).

Note that any(y) works because it will use the truthy value of each of the strings of y.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=342243&siteId=1