For loop 是否有更简洁的方法返回指定文本中包含字符组合的单词
我需要创建一个函数,该函数接受文本块作为参数,然后匹配并返回至少包含以下一个字符串/字符组合的任何单词:For loop 是否有更简洁的方法返回指定文本中包含字符组合的单词,for-loop,if-statement,functional-programming,nlp,append,For Loop,If Statement,Functional Programming,Nlp,Append,我需要创建一个函数,该函数接受文本块作为参数,然后匹配并返回至少包含以下一个字符串/字符组合的任何单词: - 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, pas
- 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))
如何更有效地编写此代码?您可以在
部分列表上添加另一个循环:
def f(string):
string_list = string.split()
match_list = []
part_list = ["tion", "ex", "pht", "ost", "ist", "ast"]
for word in string_list:
for part in part_list:
if part in word:
match_list.append(word)
return match_list