【问题标题】:How to match multiple words(per string) in array with a string containing multiple words如何将数组中的多个单词(每个字符串)与包含多个单词的字符串匹配
【发布时间】: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_lista_string是什么?
  • 是的,是因为分裂。看起来您需要使用循环并使用 word in sentence 之类的逻辑遍历每个短语,这是低效的。
  • 稍作修改,希望更有意义
  • 是的,整个事情已经是一个循环,所以如果我可以避免在其中运行一个循环,那就更好了。只是不知道该怎么做。

标签: python arrays string python-3.x match


【解决方案1】:

我认为您的代码没有意义。我们来分析一下words_in_string做了什么。

word_list 表示您要保留的单词列表,set(word_list) 将此列表转换为仅包含唯一元素的集合。在您的示例中,将['apples and oranges', 'a test', 'bannanas'] 转换为一组{'apples and oranges', 'a test', 'bannanas'}

接下来,a_string.split()a_string 拆分成一个列表,然后调用set 的函数intersection 得到集合的交集和a_string.split() 创建的内容。

最后,返回结果。

更清楚地说,给定一个单词列表,如果这些单词也包含在列表中,此函数将返回 a_string 中的单词。

例如:

给出["banana", "apple", "orange"]a_string = "I like banana and apple"。它将返回{"banana", "apple"}

但是如果你将列表更改为["bananas", "apple", "orange"],它只会返回{"apple"},因为banana 不等于bananas

【讨论】:

  • 我认为你不明白我在做什么
  • @Jonathan 直到现在,splitapples and oranges 更改为 ["apples", "and", "oranges"]。所以这是三个词,但不是一个词
  • 是的,我明白了。我试图弄清楚如何使它工作。 ://
  • 例如,试图使这个打印成功。即使它只匹配部分。 title = 'this is 1' word_list = ['this is','a test'] if title in word_list: print("successful") else: print("unsuccessful")
  • @Jonathan 如果您不介意性能。你可以使用return [item for item in word_list if item in a_string]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 2014-03-04
  • 1970-01-01
相关资源
最近更新 更多