짧은 프로그램을 작성하여 입력 파일을 가져 와서 구두점을 제거하고 단어 당 발생 수로 내용을 정렬 한 다음 가장 일반적인 결과 100 개를 출력 파일에 작성합니다.왜 목록 항목을 .txt 파일에 쓰는 방법이 효과가 없었습니까?
출력 파일에 결과를 기록하는 데 문제가 생겼습니다. 문제가 해결되었지만 문제가 무엇인지 알 수 없습니다.
전체 코드는 그래서 다음과 같습니다
from collections import Counter
from itertools import chain
import sys
import string
wordList = []
#this file contains text from a number of reviews
file1 = open('reviewfile', 'r+')
reviewWords = file1.read().lower()
#this file contains a list of the 1000 most common English words
file2 = open('commonwordsfile', 'r')
commonWords = file2.read().lower()
#remove punctuation
for char in string.punctuation:
reviewWords = reviewWords.replace(char, " ")
#create a list of individual words from file1
splitWords = reviewWords.split()
for w in splitWords:
if w not in commonWords and len(w)>2:
wordList.append(w)
#sort the resulting list by length
wordList = sorted(wordList, key=len)
#return a list containing the 100
#most common words and number of occurrences
words_to_count = (word for word in wordList)
c = Counter(words_to_count)
commonHundred = c.most_common(100)
#create new file for results and write
#the 100 most common words to it
fileHandle = open("outcome", 'w')
for listItem in commonHundred:
fileHandle.write (str(listItem) + "\n")
fileHandle.close()
나는 이전을 .txt 파일에 100 개 가장 일반적인 용어를 쓰기를 시도이 다음 코드를했지만, 그것은 작동하지 않았다. 아무도 이유를 설명 할 수 있습니까?
makeFile = open("outputfile", "w")
for item in CommonHundred:
makeFile.write("[0]\n".format(item))
makeFile.close()
_ 작동하지 않았습니까? 구체적으로 무엇이 문제입니까? –
마지막에 넣은 코드 스 니펫. 원래 출력 파일에이 방법을 시도했지만 빈 파일이 생성되었습니다. –