将列表合并为一个作为函数输出

Merging lists into one as a function output

我创建了一个包含字符串的变量,并创建了一个函数来遍历该字符串的每个单词,以找到相应的同义词并将其 return 添加到列表中:

import itertools
str_1 = "Help, Describe, AI, biology, data, machine learning, country"
def process_genre(str_1):
    for genre in str_1.split(", "):
        result = []
        for syn in wordnet.synsets(genre):
            for l in syn.lemmas():
                result.append(l.name())
            print(result)

process_genre(str_1)

问题是结果 return 重复输出,具体取决于同义词函数可用的同义词数量,如您在此处所见:

['aid', 'assist', 'assistance', 'help', 'assistant', 'helper', 'help', 'supporter', 'aid', 'assistance', 'help', 'avail', 'help', 'service', 'help', 'assist', 'aid', 'help', 'aid', 'help', 'facilitate', 'help_oneself', 'help', 'serve', 'help', 'help', 'avail', 'help', 'help']
['describe', 'depict', 'draw', 'report', 'describe', 'account', 'trace', 'draw', 'line', 'describe', 'delineate', 'identify', 'discover', 'key', 'key_out', 'distinguish', 'describe', 'name']
['Army_Intelligence', 'AI', 'artificial_intelligence', 'AI', 'three-toed_sloth', 'ai', 'Bradypus_tridactylus', 'artificial_insemination', 'AI']
['biology', 'biological_science', 'biology', 'biota', 'biology']
['data', 'information', 'datum', 'data_point']
[]
['state', 'nation', 'country', 'land', 'commonwealth', 'res_publica', 'body_politic', 'country', 'state', 'land', 'nation', 'land', 'country', 'country', 'rural_area', 'area', 'country']

我想要的是:

['account', 'ai', 'AI', 'aid', 'area', 'Army_Intelligence', 'artificial_insemination', 'artificial_intelligence', 'assist', 'assistance', 'assistant', 'avail', 'biological_science', 'biology', 'biota', 'body_politic', 'Bradypus_tridactylus', 'commonwealth', 'country', 'data', 'data_point', 'datum', 'delineate', 'depict', 'describe', 'discover', 'distinguish', 'draw', 'facilitate', 'help', 'help_oneself', 'helper', 'identify', 'information', 'key', 'key_out', 'land', 'line', 'name', 'nation', 'report', 'res_publica', 'rural_area', 'serve', 'service', 'state', 'supporter', 'three-toed_sloth', 'trace']

总而言之,我希望 get 作为输出:一个列表,包含我给定字符串(或列表)的所有同义词,以便将其合并到初始列表。这个想法是增加单词的数量以便稍后执行一些NLP。

我一直很难弄清楚如何到达我想去的地方,但找不到任何令人满意的东西。我相信它与 synset 格式列表有关。我无法使用 set() 函数或将不同的列表合并为一个函数。

不要 print,请改用 return。您还需要重新组织代码以在循环之前初始化 result 并在循环之后初始化 print/return。

def process_genre(str_1):
    result = []
    for genre in str_1.split(", "):
        for syn in wordnet.synsets(genre):
            for l in syn.lemmas():
                result.append(l.name())
    return result

print(process_genre(str_1))

注意。如果你真的想要

,你可以打印而不是return