【问题标题】:Is there a more concise way to returning words in a specified text with a combination of characters有没有更简洁的方法来返回指定文本中的单词与字符组合
【发布时间】: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


    【解决方案1】:

    您可以在 part_list 上添加另一个循环:

    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
    

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多