搜索文本以查看是否存在单词列表,如果存在,return 单词周围的文本?

Searching text to see if a list of words are there, and if there is, return the text around the word?

我有一个当前搜索文本的功能,以查看其中是否提到了我的任何关键字。我想将此功能增强到 return 找到的关键字和识别后的 25 个单词。我的代码在下面,但由于未识别“单词”而无法工作:

def searching(text):
    key_words = ["address","home", "location", "domicile"]
    if any(word in text for word in key_words):
        statement = text[text.find(word) + 1:].split()[0:20]
        my_return = " ".join(statement)
        return my_return 
    else:
        return "No result"

text = I have a pretty good living situation. I am very thankful for my home located in Massachusetts.

我希望我的功能是 return“位于马萨诸塞州的家”,但我遇到了错误。

NameError: name 'word' is not defined

有什么想法吗?

您可以将字符串拆分为单词并查看结果列表。

你在函数中返回,所以它在第一次迭代后就返回了,你可以在参数中提供关键字。

你期待的结果可以这样得到:

def searching(text):
    key_words = ["address","home", "location", "domicile"]
    for word in key_words:
        if word in text.split():
            statement = text[text.find(word) + 0:].split()[0:20]
            my_return = " ".join(statement)
            print(my_return)
        else:
            print("No result")

text = "I have a pretty good living situation. I am very thankful for my home located in Massachusetts."

print(searching(text))

输出

No result
home located in Massachusetts.
No result
No result

为了在第一次匹配时返回匹配,您可以这样做并删除 else

def searching(text):
    key_words = ["address","home", "location", "domicile"]
    for word in key_words:
        if word in text.split():
            statement = text[text.find(word) + 0:].split()[0:20]
            my_return = " ".join(statement)
            return my_return

text = "I have a pretty good living situation. I am very thankful for my home located in Massachusetts. You can find me at my address 123 Happy Lane."
print(searching(text))

输出

address 123 Happy Lane.