2013-11-27 5 views
0

짧은 프로그램을 작성하여 입력 파일을 가져 와서 구두점을 제거하고 단어 당 발생 수로 내용을 정렬 한 다음 가장 일반적인 결과 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() 
+0

_ 작동하지 않았습니까? 구체적으로 무엇이 문제입니까? –

+0

마지막에 넣은 코드 스 니펫. 원래 출력 파일에이 방법을 시도했지만 빈 파일이 생성되었습니다. –

답변

3

그 같은 중괄호,해야한다 :

makefile.write("{0}\n".format(item)) 

실행이 어떻게되는지 : 당신이 원하는 경우

a = "[0]".format("test") 
print(a) 

b = "{0}".format("test") 
print(b) 

여기에 "포맷 문자열 구문"을 검색 이동 더 많은 것을 알고 싶습니다 : http://docs.python.org/3/library/string.html.

+0

맞아, 팀! 그것은 심지어 등록하지 않았다. 나는 더 나은 안경이 필요하거나 내 컴퓨터의 글꼴 크기를 늘릴 필요가 있다고 생각합니다. 고맙습니다! –

+1

0이 필요하지 않습니다. 그냥 대괄호로 처리합니다 – volcano

+0

이것은 사실입니다. 어떤 이유로 든 항상 형식 문자열에 정수를 배치하는 미학을 좋아하지만 더 간결한 형식을 사용하는 것이 더 바람직합니다. –

관련 문제