2017-09-09 58 views
0

我在教程旁邊收到語法錯誤。這感覺就像一個Python 3 getcha。先謝謝你!Python 3與lambda的語法錯誤

def lda_description(review_text, min_topic_freq=0.05): 
""" 
accept the original text of a review and (1) parse it with spaCy, 
(2) apply text pre-processing steps, (3) create a bag-of-words 
representation, (4) create an LDA representation, and 
(5) print a sorted list of the top topics in the LDA representation 
""" 

# parse the review text with spaCy 
parsed_review = nlp(review_text) 

# lemmatize the text and remove punctuation and whitespace 
unigram_review = [token.lemma_ for token in parsed_review 
        if not punct_space(token)] 

# apply the first-order and secord-order phrase models 
bigram_review = bigram_model[unigram_review] 
trigram_review = trigram_model[bigram_review] 

# remove any remaining stopwords 
trigram_review = [term for term in trigram_review 
        if not term in spacy.en.STOPWORDS] 

# create a bag-of-words representation 
review_bow = trigram_dictionary.doc2bow(trigram_review) 

# create an LDA representation 
review_lda = lda[review_bow] 

# sort with the most highly related topics first 
review_lda = sorted(review_lda, key=lambda (topic_number, freq): -freq) 

for topic_number, freq in review_lda: 
    if freq < min_topic_freq: 
     break 

    # print the most highly related topic names and frequencies 
    print ('{:25} {}'.format(topic_names[topic_number],) 
          round(freq, 3)) 

彈出的錯誤是這樣的:

File "<ipython-input-62-745b97e51bcb>", line 31 
review_lda = sorted(review_lda, key=lambda (topic_number, freq): -freq) 
             ^

語法錯誤:無效的語法

+1

[瞭解在python拉姆達並用它來傳遞多個參數]的可能的複製(https://stackoverflow.com/questions/10345278/understanding-lambda-in- python-and-using-it-pass-multiple-arguments) – sascha

+0

這不是鏈接問題的重複。這與刪除[元組參數拆包](https://www.python.org/dev/peps/pep-3113/)有關。 – skrx

+0

[Nested arguments not compiling]的可能重複(https://stackoverflow.com/questions/10607293/nested-arguments-not-compiling) – vaultah

回答

2

在Python 3,你不能使用tuple parameter unpacking了。你可以重寫拉姆達這樣:

review_lda = sorted(review_lda, key=lambda topic_and_freq: -topic_and_freq[1]) 
+0

順便說一句,最好使用'sorted'的'reverse = True'參數而不是減去。 – skrx

+1

我不知道Python 3不支持元組解包。這解決了我的問題。非常感謝! – M4cJunk13