我创建了一个包含字符串的变量,并创建了一个函数来迭代该字符串的每个单词,以查找相应的同义词并将其返回到列表中:
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)
问题是,结果返回重复输出,这取决于同义词函数上可用的同义词数,如下所示:
['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作为输出:一个列表,包含给定字符串(或list )的所有同义词,以便将其合并到初始列表中。这样做的目的是增加单词的数量,以便稍后执行NLP。
我一直很难找到我想去的地方,但却找不到任何令人满意的东西。我认为这与同步格式的列表有关。由于函数的原因,我不能使用set() into或将不同的列表合并到一个列表中。
发布于 2021-10-24 13:43:05
不要使用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))
注意:如果您真的想要的话,可以打印而不是返回。
https://stackoverflow.com/questions/69697314
复制相似问题