0

I am getting multiple lists as an output to a function. I want to combine all the lists and form only one list. Please help

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
Raghav Shaligram
  • 309
  • 4
  • 11
  • 1
    possible duplicate of [Making a flat list out of list of lists in Python](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – Kevin Jul 26 '14 at 12:49
  • The way you have written your code, after the first word in the tokens is processed, your function will return; because `return final` is in the body of the `for` loop. Are you sure this is what you want? – Burhan Khalid Jul 27 '14 at 11:07

2 Answers2

0

Use this wherever you are using words function (which is a list of lists according to your question):

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

sgp
  • 1,738
  • 6
  • 17
  • 31
0

Once your code is corrected I find no problem with function words() returning anything other than a flat list. If there is some input that reproduces the problem please update your question with it.

The correction is to pass args directly into join(), not to wrap it in a list.

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']
mhawke
  • 84,695
  • 9
  • 117
  • 138