2013-06-17 2 views
-1
import os 
import re 
import sys 
sys.stdout=open('f1.txt','w') 
from collections import Counter 
from glob import glob 

def removegarbage(text): 
    text=re.sub(r'\W+',' ',text) 
    text=text.lower() 
    return text 

folderpath='d:/induvidual-articles' 
counter=Counter() 


filepaths = glob(os.path.join(folderpath,'*.txt')) 

num_files = len(filepaths) 

with open('topics.txt','r') as filehandle: 
    lines = filehandle.read() 
    words = removegarbage(lines).split() 
    counter.update(words) 


for word, count in counter.most_common(): 
    probability=count//num_files 
    print('{} {} {}'.format(word,count,probability)) 

내가 제로 나누기 오류가 점점 오전 : 라인 확률 제로 에 의해 플로트 부문 = // NUM_FILES 파이썬에서 제로 나누기 오류를 해결하는 방법은 무엇입니까?

내가 어떻게 그것을 수습 할

계산?

난의 형식으로 내 출력을 필요 단어, 계산, 확률

Plz은 도움을!

+0

그래서'num_files'는 0입니다. 정확한 파일 경로를 얻었습니까? –

+1

"유도 형"- 정말요? – RichieHindle

+0

예! 여기에서 카운트 값은 1-10 범위에 있고 num_files는 20,000 범위에 있습니다. –

답변

8

귀하의 num_files 변수는 folderpath='d:/induvidual-articles'가 올 경우 (induvidual는 철자가 있지만, 원래 디렉토리 유사 맞춤법이 틀린 수) 0

확인합니다.

+0

또한 folderpath = 'd \\ individual-articles'는 체재. – vamosrafa

+0

예! 작동했습니다! thanks –

+1

@vamosrafa : 앞으로 슬래시도 작동합니다. –

1

경로가 존재하는지 확인하십시오. 그렇다면 디렉토리에 적어도 .txt 파일이 하나 있는지 확인하십시오. 그리고 if 블록 내에서 for 루프 전체를 이동하십시오.

 

if num_files: 
    for word, count in counter.most_common(): 
     ... 
else: 
    print "No text files found!" 
 
관련 문제