【发布时间】:2020-12-18 16:40:51
【问题描述】:
我需要创建一个函数,该函数接受一个文本块作为参数,然后匹配并返回至少包含以下字符串/字符组合之一的任何单词:
- tion (as in navigation, isolation, or mitigation)
- ex (as in explanation, exfiltrate, or expert)
- ph (as in philosophy, philanthropy, or ephemera)
- ost, ist, ast (as in hostel, distribute, past)
我使用了一个 for 循环来搜索这些模式并将其附加到一个列表中:
def f(string):
string_list = string.split()
match_list = []
for word in string_list:
if "tion" in word:
match_list.append(word)
if "ex" in word:
match_list.append(word)
if "pht" in word:
match_list.append(word)
if "ost" in word:
match_list.append(word)
if "ist" in word:
match_list.append(word)
if "ast" in word:
match_list.append(word)
return match_list
print (f(text))
我怎样才能更有效地编写这段代码?
【问题讨论】:
标签: for-loop if-statement functional-programming nlp append