繁体   English   中英

Python - 如何检查列表中字符串中是否包含多个单词

[英]Python - How to check if multiple words in string in a list

我有这段代码:

intents = ['hello world', 'random string']

phrase = input(Enter your message: )

if phrase in intents:
    print('Found')

我如何在不输入意图中的确切字符串的情况下检查意图中的短语,如果它只是一个词很容易但多个词它不会像那样工作:

Enter your message: hello world this python
>>> Found

你把逻辑搞反了。

for intent in intents:
    if intent in phrase:
        print('Found')
        break

对于这个例子,你可以改变你的逻辑而不是检查phrase in intents ,检查intents in phrase

IE:

intents = ['hello world', 'random string']

phrase = input(Enter your message: )

for intent in intents:
  if intent in phrase:
    return True 

这是假设输入总是大于intent

你可以添加一个长度检查

基本上检查较小的 str 是否在较大的 str 中,而不是相反。

我想你也可以用any东西做一些花哨的把戏

喜欢

is_in = any([i in phrase for i in intents] + [j in intents for j in phrase])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM