簡體   English   中英

Lambda的Python 3語法錯誤

[英]Python 3 Syntax Error with lambda

在教程旁邊,我遇到語法錯誤。 感覺就像是Python 3陷阱。 先感謝您!

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

SyntaxError:語法無效

在Python 3中,您不能再使用元組參數解包了。 您可以通過以下方式重寫lambda:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM