为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕无忌1623718 2023-09-19 14:09:59
我有一个功能,当前可以搜索文本以查看其中是否提到了我的任何关键字。我想增强此功能以返回找到的关键字以及识别后的 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.我希望我的函数返回“位于马萨诸塞州的家”,但我收到错误。NameError: name 'word' is not defined有任何想法吗?
查看完整描述

1 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

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


您正在函数中返回,因此它只是在第一次迭代后返回,您可以在参数中提供关键字。


您期望的结果可以这样获得:


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.


查看完整回答
反对 回复 2023-09-19
  • 1 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信