2016-01-23 96 views
2

我無法得到任何東西寫在我的outut文件(word_count.txt)。無法獲得獨特的字/詞計數器的工作 - Python

我希望腳本在我的phrases.txt文檔中查看所有500個短語,並輸出所有單詞的列表以及它們出現的次數。

from re import findall,sub 
    from os import listdir 
    from collections import Counter 

    # path to folder containg all the files 
    str_dir_folder = '../data' 

    # name and location of output file 
    str_output_file = '../data/word_count.txt' 

    # the list where all the words will be placed 
    list_file_data = '../data/phrases.txt' 

    # loop through all the files in the directory 
    for str_each_file in listdir(str_dir_folder): 
     if str_each_file.endswith('data'): 

    # open file and read 
    with open(str_dir_folder+str_each_file,'r') as file_r_data: 
     str_file_data = file_r_data.read() 

    # add data to list 
    list_file_data.append(str_file_data) 

    # clean all the data so that we don't have all the nasty bits in it 
    str_full_data = ' '.join(list_file_data) 
    str_clean1 = sub('t','',str_full_data) 
    str_clean_data = sub('n',' ',str_clean1) 

    # find all the words and put them into a list 
    list_all_words = findall('w+',str_clean_data) 

    # dictionary with all the times a word has been used 
    dict_word_count = Counter(list_all_words) 

    # put data in a list, ready for output file 
    list_output_data = [] 
    for str_each_item in dict_word_count: 
     str_word = str_each_item 
     int_freq = dict_word_count[str_each_item] 

     str_out_line = '"%s",%d' % (str_word,int_freq) 

     # populates output list 
     list_output_data.append(str_out_line) 

    # create output file, write data, close it 
    file_w_output = open(str_output_file,'w') 
    file_w_output.write('n'.join(list_output_data)) 
    file_w_output.close() 

任何幫助將是巨大的(尤其是如果我能輸出列表中的實際輸出「單」字。

非常感謝。

+1

您在粘貼的代碼中存在縮進問題。從'with'語句縮進行以將它們放入循環中。 – kaveh

+0

嘿西蒙,它看起來像你可能是新來的SO。如果您覺得答案可以解決問題,請點擊綠色複選標記將其標記爲「已接受」。這有助於將注意力集中在仍然沒有答案的舊版SO上。 –

+0

謝謝@robertrodkey全部完成。週末愉快。 –

回答

3

將是有益的,如果我們得到了更多的這些代碼有一些主要的縮進問題,一旦我解決了這些問題,還有很多其他的邏輯錯誤需要解決,比如你已經嘗試了什麼以及你收到了什麼類型的錯誤信息,我做了一些假設:

  • 將list_file_data分配給'../data/phrases.txt',但是然後在目錄中的所有文件中循環一次 。由於您沒有在其他地方處理多個文件,所以我刪除了該邏輯,並引用了list_file_data中列出的 文件(並添加了一小部分錯誤 處理)。如果你確實想穿過一個目錄,我建議使用os.walk() (http://www.tutorialspoint.com/python/os_walk.htm
  • 你給你的文件命名爲'pharses.txt',但是檢查文件 是否以'data'結尾。我已經刪除了這個邏輯。
  • 當findall對字符串正常工作並忽略您手動刪除的特殊字符時,您已將數據集放入列表中。在這裏測試: https://regex101.com/以確保。
  • 更改「W +」到「\ W +」 - 檢查出上述鏈接
  • 轉換到列表中的輸出循環之外是沒有必要的 - 你的dict_word_count是它有一個「iteritems」方法滾動計數器對象通過每個關鍵和價值。還將變量名稱更改爲'counter_word_count'以更準確一些。
  • 而不能手動生成CSV的,我已經導入CSV和利用writerow方法(和報價選項)下面

代碼,希望這有助於:

import csv 
import os 

from collections import Counter 
from re import findall,sub 


# name and location of output file 
str_output_file = '../data/word_count.txt' 
# the list where all the words will be placed 
list_file_data = '../data/phrases.txt' 

if not os.path.exists(list_file_data): 
    raise OSError('File {} does not exist.'.format(list_file_data)) 

with open(list_file_data, 'r') as file_r_data: 
    str_file_data = file_r_data.read() 
    # find all the words and put them into a list 
    list_all_words = findall('\w+',str_file_data) 
    # dictionary with all the times a word has been used 
    counter_word_count = Counter(list_all_words) 

    with open(str_output_file, 'w') as output_file: 
     fieldnames = ['word', 'freq'] 
     writer = csv.writer(output_file, quoting=csv.QUOTE_ALL) 
     writer.writerow(fieldnames) 

     for key, value in counter_word_count.iteritems(): 
      output_row = [key, value] 
      writer.writerow(output_row) 
+0

謝謝羅伯特,非常有幫助。該腳本現在完美地工作。 –

1

像這樣的事情?

from collections import Counter 
from glob import glob 

def extract_words_from_line(s): 
    # make this as complicated as you want for extracting words from a line 
    return s.strip().split() 

tally = sum(
    (Counter(extract_words_from_line(line)) 
     for infile in glob('../data/*.data') 
      for line in open(infile)), 
    Counter()) 

for k in sorted(tally, key=tally.get, reverse=True): 
    print k, tally[k]