簡體   English   中英

Python writerows 只將NLTK FreqDist的最后一行寫入csv文件

[英]Python writerows only writes the last row of NLTK FreqDist to a csv file

我一直在編寫 Python 代碼來使用 Python 列表 ( word_list ) 中包含的單詞查找文本文檔中包含的單詞的頻率分布該程序計算頻率分布,我可以將它們打印到屏幕上,但是當我嘗試編寫頻率分布到 .csv 文件它只會重復寫入FreqDist的最后一行, FreqDist目錄中有許多文本文件。 我的代碼如下

CIK_List = []


for filename in glob.glob(os.path.join(test_path, '*.txt')):

 CIK = re.search(r"\_([0-9]+)\_", filename) # extract the CIK from the filename

 path = nltk.data.find(filename)
 raw = open(path, 'r').read()

 tokens = word_tokenize(raw)
 words = [h.lower() for h in tokens]
 f_dist = nltk.FreqDist([s.lower() for s in words])
 print(f_dist)

 wordcount = collections.Counter()

 CIK_List.append(CIK) 
 with open(file_path, 'w+', newline= '') as csv_file:
  writer = csv.writer(csv_file)
  writer.writerow(["CIK"] + word_list)
  for m in word_list:
    print([CIK.group(1)], [f_dist[m]], end='')

  for val in CIK_List:
     writer.writerows(([val.group(1)] + [f_dist[m] for m in word_list],))

問題是對於您讀取的每個輸入文件,您創建輸出文件並寫入

看看代碼末尾的以下循環。 它有什么作用?

  for val in CIK_List:
     writer.writerows(([val.group(1)] + [f_dist[m] for m in word_list],))

CIK_List是正則表達式匹配的列表。 對於每個這樣的正則表達式匹配,我們寫出第一個匹配組(它是文件名的數字部分),然后我們寫出一些不依賴於val東西 因此,當val遍歷正則表達式匹配列表時,您會一次又一次地獲得相同的輸出。

您還多次打開文件,每個輸入文件一次,每次打開文件時,您都會丟棄之前存在的內容。

您可能想要做的是打開輸出文件一次,寫出標題行,然后,對於每個輸入文件,根據該輸入文件的內容將一行寫入輸出文件:

CIK_List = []
with open(file_path, 'w+', newline= '') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(["CIK"] + word_list)

    for filename in glob.glob(os.path.join(test_path, '*.txt')):

        CIK = re.search(r"\_([0-9]+)\_", filename) # extract the CIK from the filename

        path = nltk.data.find(filename)
        raw = open(path, 'r').read()
        
        tokens = word_tokenize(raw)
        words = [h.lower() for h in tokens]
        f_dist = nltk.FreqDist([s.lower() for s in words])
        print(f_dist)
        
        wordcount = collections.Counter()

        CIK_List.append(CIK) 
        for m in word_list:
            print([CIK.group(1)], [f_dist[m]], end='')

        writer.writerow([CIK.group(1)] + [f_dist[m] for m in word_list])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM