2014-07-26 54 views
0

我得到多個列表作爲輸出到一個函數。我想合併所有列表並僅形成一個列表。請幫助加入多個列表進入函數輸出python

def words(*args): 
    word =[args] 
    tokens = nltk.wordpunct_tokenize(''.join(word)) 
    for word in tokens: 
     final = wn.synsets(word) 
     synonyms = set() 
     for synset in final: 
      for synwords in synset.lemma_names: 
       synonyms.add(synwords) 
     final = list(synonyms) 
     dic = dict(zip(word,final)) 
     dic[word] = final 
     return final 
+1

可能的重複[在Python中使列表不在列表中](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of -lists-in-python) – Kevin

+0

你編寫代碼的方式,在標記中的第一個字被處理後,你的函數將返回;因爲'return final'在'for'循環的主體中。你確定這是你想要的嗎? –

回答

0

使用此隨時隨地可以使用單詞的功能(這是根據您的問題列表的列表):

wordlist = [word for sublist in words(args) for word in sublist]

0

一旦你的代碼是糾正我發現功能沒有問題words()返回平面列表以外的任何內容。如果有一些重現問題的輸入,請使用它更新您的問題。

該更正是將args直接傳遞到join(),而不是將其包裝在列表中。

def words(*args): 
    tokens = nltk.wordpunct_tokenize(''.join(args)) 
    for word in tokens: 
     final = wn.synsets(word) 
     synonyms = set() 
     for synset in final: 
      for synwords in synset.lemma_names: 
       synonyms.add(synwords) 
     final = list(synonyms) 
     dic = dict(zip(word,final)) 
     dic[word] = final 
     return final 

>>> words('good day', ', this is a', ' test!', 'the end.') 
['beneficial', 'right', 'secure', 'just', 'unspoilt', 'respectable', 'good', 'goodness', 'dear', 'salutary', 'ripe', 'expert', 'skillful', 'in_force', 'proficient', 'unspoiled', 'dependable', 'soundly', 'honorable', 'full', 'undecomposed', 'safe', 'adept', 'upright', 'trade_good', 'sound', 'in_effect', 'practiced', 'effective', 'commodity', 'estimable', 'well', 'honest', 'near', 'skilful', 'thoroughly', 'serious']