【问题标题】:Merging lists into one as a function output将列表合并为一个作为函数输出
【发布时间】:2021-10-24 13:40:26
【问题描述】:

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

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)

问题是结果返回重复输出,具体取决于 synonym 函数上可用的同义词数量,如您在此处看到的:

['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。

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

【问题讨论】:

    标签: python synset


    【解决方案1】:

    不要print,而是使用return。您还需要重新组织代码以在循环之前初始化 result 并在循环之后打印/返回它。

    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))
    

    注意。如果你真的想要,你可以打印而不是返回

    【讨论】:

    • 非常感谢@mozway,这很有效:D
    • 不客气,很高兴它有帮助!
    猜你喜欢
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2015-02-22
    • 2021-10-24
    • 2020-01-26
    • 2014-01-27
    相关资源
    最近更新 更多