【发布时间】:2017-09-18 01:11:51
【问题描述】:
已解决。请参阅本文底部的解决方案
我正在尝试过滤掉一个连续循环,该循环具有不断输入的字符串(来自 API)。
这是我正在使用的代码示例 -
我用这样的数组设置了一个过滤器:
filter_a = ['apples and oranges', 'a test', 'bananas']
我在 Stackoverflow 上找到的一个函数如下:
def words_in_string(word_list, a_string):
return set(word_list).intersection(a_string.split())
title = 'bananas'
#(this is a continuously looping thing, so sometimes it
# might be for example 'apples and oranges')
还有我的 if 语句:
if words_in_string(filter_a, str(title.lower())):
print(title.lower())
由于某种原因,它会检测到“香蕉”而不是“苹果和橙子”。它会跳过包含多个单词的字符串。我猜是因为 split() 但我不确定。
编辑: 这是我的意思的另一个例子:
匹配此并使其成功:
title = 'this is 1'
word_list = ['this is','a test']
if title in word_list:
print("successful")
else:
print("unsuccessful")
编辑 2:
解决方案
title = '这是 1'
word_list = ['这是','测试']
如果有(word_list 中项目的标题中的项目): 打印(“成功”) 别的: print("不成功")
【问题讨论】:
-
我们需要一个简单的例子,告诉我们
word_list和a_string是什么? -
是的,是因为分裂。看起来您需要使用循环并使用
word in sentence之类的逻辑遍历每个短语,这是低效的。 -
稍作修改,希望更有意义
-
是的,整个事情已经是一个循环,所以如果我可以避免在其中运行一个循环,那就更好了。只是不知道该怎么做。
标签: python arrays string python-3.x match