如何测试是否有任何单词与 Python 中的字符串匹配

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

我想写一个python程序来测试是否有任何短语可以匹配使用python的字符串。

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

所以我想发短信,如果列表中有任何一个可以匹配可以打印 'I love' 或 'my travel'、'all over the world'.

的字符串
any(x in string for x in list)

或者我需要使用文本挖掘来解决问题?

您当前的解决方案可能是在此给定场景中使用的最佳解决方案。如果你愿意,你可以把它封装成一个函数。

def list_in_string(slist, string):
    return any(x in string for x in slist_list)

你不能这样做:

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

因为any函数遍历整个string/list,舍弃x变量,然后简单returns一个布尔值(TrueFalse).

但是,您可以拆分 any 函数,以便获得所需的输出。

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

这将输出:

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

使用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

这将输出:

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

如果要返回True或False,肯定可以使用any(),例如:

>>> string = 'I love my travel all over the world'
>>> list_string =['I love',
          'my travel',
          'all over the world',
          'Something something',
          'blah']
>>> any(x for x in list_string if x in string)
True
>>> 

否则,您可以做一些简单的列表理解:

>>> string ='I love my travel all over the world'
>>> list_string =['I love',
          'my travel',
          'all over the world',
          'Something something',
          'blah']
>>> [x for x in list_string if x in string]
['I love', 'my travel', 'all over the world']
>>> 

根据您想要返回的内容,这两种方法都可以完美运行。

您也可以使用正则表达式,但对于如此简单的事情来说有点矫枉过正。

为了完整性,可以提到 find 方法:

_string ='I love my travel all over the world'
_list =['I love','my travel','all over the world','spam','python']

for i in range(len(_list)):
    if _string.find(_list[i]) > -1:
        print _list[i]

输出:

I love
my travel
all over the world

注意:此解决方案不如提到的in用法优雅,但如果需要找到的子字符串的位置,则可能有用。