Search code examples
pythonstringsplitphrase

how to test if there is any word matched the string in Python


I want to write a python program to test if there are any phrase can match the string using python.

string ='I love my travel all over the world'
list =['I love','my travel','all over the world']

So I want to text if there are any one of list can match that string that can print 'I love' or 'my travel','all over the world'.

any(x in string for x in list)

Or I need to use text mining to solve the problem?


Solution

  • You can't do this:

    if any(x in string for x in word_list)
        print x
    

    Because the any function iterates through the entire string/list, discards the x variable, and then simply returns a Boolean (True or False).

    You can however, just break apart your any function so that you can get your desired output.

    string ='I love traveling all over the world'
    word_list =['I love','traveling','all over the world']
    
    for x in word_list:
        if x in string:
            print x
    

    This will output:

    >>>
    I love
    traveling
    all over the world
    >>>
    

    Update using string.split() :

    string =['I', 'love','traveling','all', 'over', 'the', 'world']
    word_list =['I love','traveling','all over the world']
    count=0
    for x in word_list:
        for y in x.split():
            if y in string:
                count+=1
                if count==len(x.split()) and (' ' in x) == True:
                    print x
        count=0
    

    This will output:

    >>> 
    I love
    all over the world
    >>>