我想编写一个python程序来测试是否有任何短语可以使用python匹配字符串。
string ='I love my travel all over the world'
list =['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
函数遍历整个字符串/列表,丢弃x
变量,然后简单地返回一个布尔值(True
或False
)。
但是,您可以分解您的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
,可能会有用。