微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否有更简洁的方法来返回指定文本中包含字符组合的单词

如何解决是否有更简洁的方法来返回指定文本中包含字符组合的单词

我需要创建一个函数,该函数接受文本块作为参数,然后匹配并返回包含至少一个以下字符串/字符组合的单词:

- 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 上添加另一个循环:

fetch().then().catch(err => ...) 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。