2017-04-21 4 views
0

저는 파이썬에서 절대적인 초보자입니다. 나는 그리스어 놀이의 텍스트 분석을하고 각 단어의 단어 빈도를 세고있다. 연극은 매우 길기 때문에 전체 데이터 세트를 볼 수 없으며 파이썬 창에 공간이 충분하지 않기 때문에 빈도가 가장 낮은 단어 만 보여줍니다. 나는 그것을 .csv 파일로 변환하려고 생각하고있다. 내 전체 코드는 다음과 같습니다.사전 값을 CSV 파일로 변환하는 방법은 무엇입니까?

#read the file as one string and spit the string into a list of separate words 
input = open('Aeschylus.txt', 'r') 
text = input.read() 
wordlist = text.split() 

#read file containing stopwords and split the string into a list of separate words 
stopwords = open("stopwords .txt", 'r').read().split() 

#remove stopwords 
wordsFiltered = [] 

for w in wordlist: 
    if w not in stopwords: 
     wordsFiltered.append(w) 

#create dictionary by counting no of occurences of each word in list 
wordfreq = [wordsFiltered.count(x) for x in wordsFiltered] 

#create word-frequency pairs and create a dictionary 
dictionary = dict(zip(wordsFiltered,wordfreq)) 

#sort by decreasing frequency and print 
aux = [(dictionary[word], word) for word in dictionary] 
aux.sort() 
aux.reverse() 
for y in aux: print y 

import csv 


with open('Aeschylus.csv', 'w') as csvfile: 
    fieldnames = ['dictionary[word]', 'word'] 
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames) 


    writer.writeheader() 
    writer.writerow({'dictionary[word]': '1', 'word': 'inherited'}) 
    writer.writerow({'dictionary[word]': '1', 'word': 'inheritance'}) 
    writer.writerow({'dictionary[word]': '1', 'word': 'inherit'}) 

인터넷에서 csv 코드를 발견했습니다. 내가 얻고 자하는 것은 가장 높은 주파수에서 가장 낮은 주파수까지의 전체 데이터 목록입니다. 지금 당장이 코드를 사용하면 파이썬은 csv 부분을 완전히 무시하고 CSV 코드를 작성하지 않은 것처럼 데이터를 인쇄하는 것처럼 보입니다.

내가 의도 한 결과를보기 위해 무엇을 코딩해야하는지에 대한 아이디어가 있습니까?

감사합니다.

+0

파일을 닫아야합니다. – DrBwts

답변

0

단어가 키이고 빈도 값이 사전 인 사전이 있으므로 DictWriter은 적합하지 않습니다. csv의 열로 사용되는 몇 가지 공통 키 집합을 공유하는 매핑 시퀀스에 유용합니다. 예를 들어, 당신은 같은 수동으로 만들 때 dicts의 목록이 있었다면 :

a_list = [{'dictionary[word]': '1', 'word': 'inherited'}, 
      {'dictionary[word]': '1', 'word': 'inheritance'}, 
      {'dictionary[word]': '1', 'word': 'inherit'}] 

는 다음 DictWriter이 작업의 도구가 될 것입니다.

with open('Aeschylus.csv', 'wb') as csvfile: 
    header = ['frequency', 'word'] 
    writer = csv.writer(csvfile) 
    writer.writerow(header) 
    # Note the plural method name 
    writer.writerows(aux) 

파이썬 :

dictionary = {'inherited': 1, 
       'inheritance': 1, 
       'inherit': 1, 
       ...: ...} 

, 당신은 이미 CSV로 쓰기 위해 완벽 aux(freq, word)쌍 정렬 된 목록을 구축했습니다 :하지만 그 대신 단일 dictionary 같이가 csv 부분을 완전히 무시하고 csv 코드를 작성하지 않은 것처럼 데이터를 인쇄하는 것 같습니다.

다소 이상합니다.

dictionary[word],word 
1,inherited 
1,inheritance 
1,inherit 

귀하의 주파수 계산 방법도 개선 될 수 : 적어도 당신이 포함 된 파일 Aeschylus.csv 쪘해야한다. 순간

#create dictionary by counting no of occurences of each word in list 
wordfreq = [wordsFiltered.count(x) for x in wordsFiltered] 

정도로 O (n²), wordsFiltered 각 단어리스트 wordsFiltered을 반복한다. 대신 파일에서 단어를 반복하고 필터링하고 개수를 계산할 수 있습니다.

for word, freq in wordfreq.most_common(): 
     print(word, freq) 

를 그리고/또는 CSV로 쓰기 : 가장 일반적인에서 시작, 단어와 자신의 주파수를 인쇄, 이전, 다음

from __future__ import print_function 
from collections import Counter 
import csv 

# Many ways to go about this, could for example yield from (<gen expr>) 
def words(filelike): 
    for line in filelike: 
     for word in line.split(): 
      yield word 

def remove(iterable, stopwords): 
    stopwords = set(stopwords) # O(1) lookups instead of O(n) 
    for word in iterable: 
     if word not in stopwords: 
      yield word 

if __name__ == '__main__': 
    with open("stopwords.txt") as f: 
     stopwords = f.read().split() 

    with open('Aeschylus.txt') as wordfile: 
     wordfreq = Counter(remove(words(wordfile), stopwords)) 

: 파이썬은 Counter라는 해쉬 객체를 카운트하는 전문 사전을 가지고 :

# Since you're using python 2, 'wb' and no newline='' 
    with open('Aeschylus.csv', 'wb') as csvfile: 
     writer = csv.writer(csvfile) 
     writer.writerow(['word', 'freq']) 
     # If you want to keep most common order in CSV as well. Otherwise 
     # wordfreq.items() would do as well. 
     writer.writerows(wordfreq.most_common()) 
+0

이전 코드를 유지하고 싶다면 어떻게해야합니까?나는이 일에 정말 새로운 것이므로 당신이 나를 위해 썼다는 것을 이해할 수 없으며 완벽하게 작동합니다. 어떻게 이전 코드를 사용하여 CSV에 데이터를 쓸 수 있는지 이해하고 싶습니다. –

+0

나는 도망가는 것에 대해 사과드립니다. 그러나 여전히 'DictWriter'는 당신의 데이터에 잘 맞지 않는다. 사전이 있어도 기본'csv.writer'를 사용하여'sorted (dictionary.items(), key = itemgetter (1), reverse = True) '를 작성하는 것이 좋습니다. 나는 나중에 대답을 업데이트 할 것이다. –

+0

안녕하세요, 'writer.writerows (aux)'로 편집 된 코드를 사용해 보았습니다.하지만 파이썬은 여전히 ​​데이터를 .csv 파일에 저장하는 것으로 보이지 않습니다. 나는 '사전 [단어]'과 '단어'인 두 개의 머리말 만 얻는다. 파일을 닫는 것과 관련이있을 수 있습니까? –