2017-12-10 1 views
0

nltk를 사용하여 학위에 따라 구문에서 단어의 빈도 분포를 가져 오려고합니다. "TypeError : unhashable type : 'list'"를 보여주고 있습니다. 문제가 무엇인지 이해하지 마십시오. 도와주세요.nltk.FreqDist() 함수에서 "TypeError : unhashable type : 'list'"를 사용 중입니다.

P.S : 코드에는 많은 버그가 있으므로 신경 쓸 필요가 없습니다. 저는 파이썬에 대한 멍청이이기 때문에 많은 프로그램의 코드 스 니펫을 사용하여 키워드 추출기를 만들려고합니다. 누구든지 다른 버그를 밝히기를 원한다면 환영합니다.

코드 :

from __future__ import division 
import operator 
import nltk 
import string 

def isPunct(word): 
    return len(word) == 1 and word in string.punctuation 

def isNumeric(word): 
    try: 
    float(word) if '.' in word else int(word) 
    return True 
    except ValueError: 
    return False 

class KeyExt: 

    def __init__(self): 
    self.stopwords = set(nltk.corpus.stopwords.words()) 
    self.top_fraction = 1 

    def _generate_candidate_keywords(self, sentences): 
    phrase_list = [] 
    for sentence in sentences: 
     words = map(lambda x: "|" if x in self.stopwords else x, nltk.word_tokenize(sentence.lower())) 
     phrase = [] 
     for word in words: 
     if word == "|" or isPunct(word): 
      if len(phrase) > 0: 
      phrase_list.append(phrase) 
      phrase = [] 
     else: 
      phrase.append(word) 
    return phrase_list 

    def _calculate_word_scores(self, phrase_list): 
    word_freq = nltk.FreqDist() 
    word_degree = nltk.FreqDist() 
    for phrase in phrase_list: 
     degree = [x for x in phrase if not isNumeric(x)] 
     for word in phrase: 
     word_freq[word]=word_freq[word]+1 
     word_degree[word, degree]=word_degree[word, degree]+1 
    for word in word_freq.keys(): 
     word_degree[word] = word_degree[word] + word_freq[word] 
    word_scores = {} 
    for word in word_freq.keys(): 
     word_scores[word] = word_degree[word]/word_freq[word] 
    return word_scores 

    def _calculate_phrase_scores(self, phrase_list, word_scores): 
    phrase_scores = {} 
    for phrase in phrase_list: 
     phrase_score = 0 
     for word in phrase: 
     phrase_score += word_scores[word] 
     phrase_scores[" ".join(phrase)] = phrase_score 
    return phrase_scores 

    def extract(self, text, incl_scores=False): 
    sentences = nltk.sent_tokenize(text) 
    phrase_list = self._generate_candidate_keywords(sentences) 
    word_scores = self._calculate_word_scores(phrase_list) 
    phrase_scores = self._calculate_phrase_scores(phrase_list, word_scores) 
    sorted_phrase_scores = sorted(phrase_scores.items(), key=operator.itemgetter(1), reverse=True) 
    n_phrases = len(sorted_phrase_scores) 
    if incl_scores: 
     return sorted_phrase_scores[0:int(n_phrases/self.top_fraction)] 
    else: 
     return map(lambda x: x[0], 
     sorted_phrase_scores[0:int(n_phrases/self.top_fraction)]) 

def test(): 
    search=input("Enter Text: ") 
    ke = KeyExt() 
    keywords = ke.extract(search, incl_scores=True) 
    print (keywords) 

if __name__ == "__main__": 
    test() 

전체 역 추적 : 당신이 listdict A와 키를 사용하려고 할 때

Traceback (most recent call last): File "C:\Users\SAURAV 
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line 
81, in <module> 
    test() File "C:\Users\SAURAV DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line 
77, in test 
    keywords = ke.extract(search, incl_scores=True) File "C:\Users\SAURAV 
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line 
64, in extract 
    word_scores = self._calculate_word_scores(phrase_list) File "C:\Users\SAURAV 
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line 
44, in _calculate_word_scores 
    word_degree[word, degree]=word_degree[word, degree]+1 TypeError: unhashable type: 'list' 
+1

전체 추적 표시 (줄 번호와 원인 코드 줄 포함) –

+0

[오류 잡기] (https://docs.python.org/3/tutorial/errors.html#handling-exceptions) 및 inspect/예외 상황에서 관련 데이터를 인쇄하여 어떤 일이 벌어지는 지 확인하십시오. 또한 전략적 위치에서 데이터를 인쇄하여 디버깅에 도움을 줄 수도 있습니다. – wwii

+0

ok는 초 단위로 수행합니다 –

답변

0

이 오류가 발생합니다. list은 해시 가능하지 않으므로 키에 사용할 수 없습니다 (예 : tuple을 사용할 수 있음). 당신이 감지 원인 학위 자체가 list입니다하지 않습니다 word_degree에 대한 인덱스로 학위를 사용하는이 라인

word_degree[word, degree]=word_degree[word, degree]+1 

에 경우

.

+0

그럼 나에게 해결책을 제안 할 수있다 –

+0

@IncognitoPossum 방금 오류가 무엇인지 대답했다. 'word_degree'와'degree'와 같은 질문에이 세부 사항을 추가하십시오. –

+0

'word_degree'는 단어의 학위 또는 우선 순위를 나타냅니다. 적어도 그것이 내가하고 싶은 일입니다. 죄송 지연에 대한 답변. 열병으로 고통 받고 있었다. –

관련 문제