from collections import Counter
from glob import iglob
import re
import os
def remove_garbage(text):
"""Replace non-word (non-alphanumeric) chars in text with spaces,
then convert and return a lowercase version of the result.
"""
text = re.sub(r'\W+', ' ', text)
text = text.lower()
return text
topwords = 50000
folderpath = 'd:/jktextall/'
counter = Counter()
for filepath in iglob(os.path.join(folderpath, '*.txt')):
with open(filepath) as file:
counter.update(remove_garbage(file.read()).split())
file1 = open("jkwords1.txt","w")
for word, count in counter.most_common(topwords):
file1.write (str(count) +"," + word + "\n")
file1.close
위 코드를 수정하여 텍스트 파일 jkwords1.txt
에 출력을 작성했습니다. 텍스트 파일에 아무 것도 기록되지 않습니다. 그러나 print (word,count)
은 파이썬 콘솔에서 출력을 생성합니다.파이썬 루프 출력이 텍스트 파일이 아님
그러나 file1.write
대신 print(count,word)
을 사용하면 화면이 출력됩니다.
사용'...'반드시 모든 것이 제대로 디스크에 기록됩니다 확인합니다. –