我正在使用以下功能来确定文本是否包含列表中的单词(或表达式):
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'“。
请明确一点,我对同时包含两个词的文本感兴趣。我想拥有一个搜索这些组合的功能,而无需手动输入所有这些条件。
答案 0 :(得分:0)
您可以重写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
答案 1 :(得分:0)
执行此操作的更好方法可能是先将文本转换为列表,例如
a = ["white", "clouds"]
然后列出您的关键字列表:
b = ["clouds", "red"]
然后做:
>>> set(a).intersection(b)
返回:
{'clouds'}