【问题标题】:if allwords in title: matchif allwords in title: 匹配
【发布时间】:2016-08-24 17:56:40
【问题描述】:

使用 python3,我有一个单词列表,例如: ['foot', 'stool', 'carpet']

这些列表的长度从 1 到 6 左右不等。我有成千上万的字符串要检查,并且需要确保所有三个单词都出现在标题中。在哪里: 'carpet stand upon the stool of foot balls.' 是一个正确的匹配,因为所有的词都出现在这里,即使它们是乱序的。

我想了很长时间,我唯一能想到的就是某种迭代,例如:

for word in list: if word in title: match!

但这给了我像'carpet cleaner' 这样的结果,这是不正确的。我觉得好像有某种捷径可以做到这一点,但如果不使用过多的list(), continue, break 或其他我还不熟悉的方法/术语,我似乎无法弄清楚。等等等等。

【问题讨论】:

  • 您希望recarpeted footstool 匹配吗?

标签: python list python-3.x matching word


【解决方案1】:

你可以使用all():

words = ['foot', 'stool', 'carpet']
title = "carpet stand upon the stool of foot balls."

matches = all(word in title for word in words)

或者,用非any()not in 反转逻辑:

matches = not any(word not in title for word in words)

【讨论】:

  • 如果不应该匹配子字符串,您可能需要拆分。
  • @PadraicCunningham。还要避免匹配 recarpeted 之类的东西。
  • 好点,谢谢! Nltk 的 word tokenizer 可能是分割成单词并处理所有标点符号的更好选择。
  • 这是一个更简单的选项,它只是使用普通 Python 去除标点符号:stackoverflow.com/a/17951315/2988730
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 2020-05-08
相关资源
最近更新 更多