簡體   English   中英

Python:將兩個不同的字典寫到兩個不同的csv文件中

[英]Python: writing two different dictionaries out to two different csv files

我的程序查看文本文件的文件夾,並生成我正在查看的“ SS”和“ DS”兩個功能的計數以及它們出現的次數。 因此,我建立了一個字典,列出了該功能及其在文本中出現的次數。

我希望我的SS詞典寫出到一個csv文件,而DS詞典寫出到另一個csv文件。

到目前為止,這是我的代碼:

import glob
import re

path = "tagged texts\*.txt"

#establish counts and dictionaries
list_SS = []
list_DS = []
SScounts = {}
DScounts = {}

#generate counts of the features
for file in glob.glob(path):
    line_count = 0
    with open(file, encoding='utf-8', errors='ignore') as file_in:
        text = file_in.readlines()
        for line in text:
            word = line.split('_')
            if word[2] == "SS":
                list_SS.append(word[0])
            elif word[2] == "DS":
                list_DS.append(word[0])

#create dictionary for SS and write out results to file
file1_out = open("SS_counts.csv", "w+")
for w in list_SS:
    SScounts[w] = SScounts.get(w,0) + 1
for i in sorted(SScounts, key = SScounts.get, reverse=True):
    file1_out.write(str(i) + "," + str(SScounts[i]) + "\n")

#create dictionary for DS and write out results to file
file2_out = open ("DS_counts.csv", "w+")
for w in list_DS:
    DScounts[w] = DScounts.get(w,0) + 1
for i in sorted(DScounts, key = DScounts.get, reverse=True):
    file2_out.write(str(i) + "," + str(DScounts[i]) + "\n")

SS字典可以很好地顯示出來,這就是csv文件中的結果:

nisha,41
rasha,19
rikusha,13
apisha,11
nishashi,8
...

問題是第二個文件DS文件變成空白,其中沒有任何內容。 在擺弄字典中的變量名之前,我將獲得SS字典的結果寫到兩個文件中。

在問了教授之后,我創建了兩本詞典,他說可以用一本字典來做,但是使用兩本字典會更簡單。 而且我想我可以為DS結果編寫一個單獨的python腳本,但我想兩者都在同一個腳本中完成。

oo,怎么了? 為什么第二個字典不寫到第二個文件?

StackOverflow的公民無法運行您的代碼。 它通常有助於創建其他人可以運行的最小,完整和可驗證的示例。

一個關鍵問題: list_SSlist_DS是否有數據? 刪除所有以file1_out開頭的代碼,而使用以下代碼:

assert list_SS
assert list_DS

如果這些斷言失敗,那么您將大大縮小問題的范圍。

另一個關鍵問題:如果消除亂碼和文件讀取,是否可以重現該問題? 大致像這樣:

list_SS = []
list_DS = []
SScounts = {}
DScounts = {}

text = [
    'an example line from your data files...',
    'ditto...',
    '...',
]

for line in text:
    word = line.split('_')
    if word[2] == "SS":
        list_SS.append(word[0])
    elif word[2] == "DS":
        list_DS.append(word[0])

assert list_SS
assert list_DS

在這一點上,您將獲得StackOverflow可以幫助的某些東西,但是到那時您可能不需要我們了。

暫無
暫無

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

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