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.
添加回答
舉報