2014-02-10 4 views
0

나는 위치 경로에 저장된 파일에 포함 된 단어의 빈도 및 문서 빈도를 찾기 위해 몇 가지 코드를 작성했습니다. 각 파일은 cleanDoc() 함수를 통해 텍스트 파일에서 단어를 가져 오며 전 표제어로 용어 빈도를 파일에 넣으므로 모든 문서의 모든 단어를 찾아서 계산해야합니다. 아무도 내가 그것을 어떻게 구현해야하는지 말할 수 있습니까? 나는 NLTK 만 사용하고 있습니다.단어 빈도 및 문서 단어 빈도

import collections 
import os.path 
import glob 
import nltk 

wdict = set() 

path = "C://Python27//Corpus Files//*.*" 

#this function cleans up a doc (removes stopwords etc) 
def cleanDoc(doc): 
    stopset = set(nltk.corpus.stopwords.words('english')) 
    stemmer = nltk.PorterStemmer() 
    tokens = nltk.WordPunctTokenizer().tokenize(doc) 
    clean = [token.lower() for token in tokens if token.lower() not in stopset and len(token) > 3 and token.isalpha()] 
    final = [stemmer.stem(word) for word in clean] 
    return final 

for text in glob.glob(path): 

    f = open(text) 
    data= f.read() 
    words = cleanDoc(data) 
    wdict.update(words) 

답변

0

당신은이 단어를 계산 nltk.probability에서의 FreqDist 객체를 사용할 수 있습니다. 나중에 freq.items() 또는 freq['word']과 같은 dict-like 키 - 값 인터페이스와 메소드를 사용하여 탐색 할 수도 있고 matplotlib을 사용하여 결과를 플로팅 할 수도 있습니다.

import collections 
import os.path 
import glob 
import nltk 
from nltk.probability import FreqDist 


term_frequency = {} 

path = "C://Python27//Corpus Files//*.*" 

#this function cleans up a doc (removes stopwords etc) 
def cleanDoc(doc): 
    stopset = set(nltk.corpus.stopwords.words('english')) 
    stemmer = nltk.PorterStemmer() 
    tokens = nltk.WordPunctTokenizer().tokenize(doc) 
    clean = [token.lower() for token in tokens if token.lower() not in stopset and len(token) > 3 and token.isalpha()] 
    final = [stemmer.stem(word) for word in clean] 
    return final 

for text in glob.glob(path): 
    f = open(text) 
    data = f.read() 
    words = cleanDoc(data) 
    numbers_of_words = len(words) 
    freq = FreqDist(all_words) 
    # term_frequency is a dict which structure is like: 
    # { 
    #  'path_to_file': 
    #   {'term': 13.4, 'another_term': 15}, 
    #  'another_file': 
    #   {'term2': 12, 'foo': 15} 
    # } 
    for term in freq.keys(): 
     if isintance(term_frequency[text], dict): 
      term_frequency[text][term] = freq[term]/numbers_of_words 
     else: 
      term_frequency[text] = {term: freq[term]/numbers_of_words} 

참조 : 그것은 경로에 저장된 모든 문서에서 모든 단어를 고려하지 않습니다 https://nltk.googlecode.com/svn/trunk/doc/api/nltk.probability.FreqDist-class.html

+0

. 단지 몇 가지 용어에 대한 결과가 있습니다. – DummyGuy

+0

내 잘못이야, 지금 고칠거야. –

+0

죄송하지만 작동하지 않습니다. 나는 그 문서를 참고로 단어 수를 원한다. – DummyGuy

관련 문제