python - Python:在文本中查找关键字组合
问题描述
我正在使用以下函数来确定文本是否包含列表中的单词(或表达式):
def is_in_text(text, lista=[]):
return any(i in text for i in lista)
我可以将我想在文本中找到的单词和表达式的列表传递给这个函数。例如,下面的代码:
text_a = 'There are white clouds in the sky'
print(is_in_text(text_a, ['clouds in the sky']))
将返回
True
如果我对提到“云”和“天空”的文本感兴趣,这很有效。但是,如果文本略有不同,我可能不再检测到它。例如:
text_b = 'There are white clouds in the beautiful sky'
print(is_in_text(text_b, ['clouds in the sky']))
将返回 False。
如何修改此功能以查找包含两个单词但不一定按预定顺序的文本?在这个例子中,我想寻找“'clouds' + 'sky'”。
为了清楚起见,我对包含这两个词的文本感兴趣。我想要一个搜索这些组合的功能,而不必手动输入所有这些条件。
解决方案
您可以重新编写is_in_text
以检查您要检查的任何单词列表中的每个单词是否在字符串中:
def is_in_text(text, lista=[]):
isin = True
for word in lista:
isin = isin and (word in text)
return isin
例如
text_a = 'There are white clouds in the sky'
print(is_in_text(text_a, ['cloud', 'sky']))
返回True
尽管
text_a = 'There are white clouds in the sky'
print(is_in_text(text_a, ['dog', 'sky']))
返回False
但是,这需要您知道要匹配两个字符串的单词。如果要检查字符串中的所有单词,可以将字符串拆分为空格。
例如
text_b = 'There are white clouds in the beautiful sky'
print(is_in_text(text_b, 'clouds in the sky'.split(' ')))
现在返回True
编辑:
因此,我认为您可能应该重新考虑您要尝试做的事情,因为这将非常脆弱,但是根据您所描述的内容,这是可行的:
def is_in_text(text, lista=[]):
isin = False
for string in lista:
sub_isin = True
for substr in string.split(' '):
sub_isin = sub_isin & (substr in text)
isin = isin or sub_isin
return isin
例如
text_a = 'There are white clouds in the sky'
print(is_in_text(text_a, ['rain', 'cloud sky']))
评估为True
尽管
text_a = 'There are white clouds in the sky'
print(is_in_text(text_a, ['rain', 'dog sky']))
评估为False
推荐阅读
- java - 多个数据源的 Spring Boot 错误(对 DialectResolutionInfo 的访问不能为空)
- database - 如何制作点“。” 下划线 '_' 的行为类似于 MongoDB 中 $text 索引中的空格
- python - Index of an element in a nested list
- visual-c++ - 对于给定的整数 n,找到 n 后面是 10 的倍数的数
- c - 我们如何使用 C 中的指针算术仅打印出两个相同符号之间的字符串的一部分
- json - 无法在 Gitlab Yaml 管道中编码 JSON
- redis - 如何检查每秒访问 Redis 的平均请求数
- json - 从 React 中的 JSON 本地文件中获取数据
- javascript - 不返回承诺时的nodemailer延迟
- python - 带有回调的 kivy Urlrequest 在移动设备上抛出错误,但在笔记本电脑上却没有,为什么?