簡體   English   中英

Python - csv編寫器按列寫,而不是行

[英]Python - csv writer write by column, not row

我正在處理一系列文本文件,其中我想保留一些變量。 我試圖將這些變量保存在csv文件中。 每個文本文件將從此csv文件中獲取1行和N列。我可能有1000個或更多文件,這將導致csv文件具有1000行和N列(N可以是10或更多或更少)。 我想使用以下代碼

res=[variable1, variable2, variable3, ..., variableN]
csvfile = "summary.csv"
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(res)

問題是它在每一行寫入一個值,然后移動到下一個變量的下一行..而我希望每個文本文件的所有變量占用1行(和N列)。 我應該如何更改代碼才能使其正常工作?

編輯

import re
import collections
from collections import Counter
import csv
import sys


wanted1 = re.findall('\w+', open('words1.csv').read().lower())
wanted2 = re.findall('\w+', open('words2.csv').read().lower())
for f in sys.argv[1:]:
    words = re.findall('\w+', open('f').read().lower())
    cnt = Counter()
    cnt1 = 0
    cnt2 = 0
    cntWords = 0
    for word in words:
        cntWords += 1
            if word in wanted1:
                cnt[word] += 1
                cnt1 += 1
            if word in wanted2:
                cnt[word] += 1
                cnt2 += 1   
print cnt1, cnt2, cntWords
res=[cnt1, cnt2, cntWords]
csvfile = "summary.csv"
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerow(res)

在這種情況下,這些變量中的每一個都是數字。 我還想添加一些包含字符串內容的變量。 每個文本文件將占用1行。 每個變量將占用一個單元格。

例如,cnt1可以具有值10000,cnt2可以具有值2000,cntWords可以具有值30000等。

我試圖更改我的代碼來處理文件夾中的所有.txt文件,但現在我收到一個錯誤

  File "countWords.py", line 29
    writer = csv.writer(output, lineterminator='\n')
                                                   ^
IndentationError: unindent does not match any outer indentation level

編輯2:Output.csv應該是這樣的

       Column 1 Column 2 Column 3
Row 1: Cnt1     Cnt2     CntWords      (all row 1 values should be derived from file1.txt)
Row 2: Cnt1     Cnt2     CntWords      (all row 2 values should be derived from file2.txt)
Row 3: Cnt1     Cnt2     CntWords      (all row 3 values should be derived from file3.txt)
Row 4: Cnt1     Cnt2     CntWords      (all row 4 values should be derived from file4.txt)
Row 5: Cnt1     Cnt2     CntWords      (all row 5 values should be derived from file5.txt)
Row 6: Cnt1     Cnt2     CntWords      (all row 6 values should be derived from file6.txt)

通過Cnt1我的意思是Cnt1的值,通過Cnt2我的意思是Cnt2的值,通過CntWords我的意思是CntWords的值(這些將是數字)

       Column 1 Column 2 Column 3
Row 1: 5000     3000     10000      (all row 1 values should be derived from file1.txt)
Row 2: 510     420     1423      (all row 2 values should be derived from file2.txt)

這意味着輸入的是2個文本文件,其中第一個有5000個單詞列表1個單詞,3000個單詞列表單詞2個,10000個單詞單詞,而第二個文本文件有510個單詞單詞列表,420個單詞單詞清單2,總共1423個單詞。

如果您只想將3個計數器寫入CSV文件,那么只需在循環中寫入CSV文件即可。 在循環外創建CSV編寫器,並在處理文件時向其寫入行:

find_words = re.compile(r'\w+').findall

# create *sets* for faster membership tests
wanted1 = set(find_words(open('words1.csv').read().lower()))
wanted2 = set(find_words(open('words2.csv').read().lower()))

csvfile = "summary.csv"
with open(csvfile, "wb") as output:
    writer = csv.writer(output)

    for f in sys.argv[1:]:
        cnt1 = cnt2 = cntWords = 0

        with open(f) as inputfile:
            for line in inputfile:
                for word in find_words(line.lower()):
                    cntWords += 1
                    if word in wanted1:
                        cnt1 += 1
                    if word in wanted2:
                        cnt2 += 1   

        writer.writerow([cnt1, cnt2, cntWords])

我還用快速成員資格測試替換了你wanted*列表(而不是每次在常數時間內找到單詞時掃描整個列表),並逐行掃描輸入文件以避免破壞內存。

第18行的縮進錯誤,它必須看起來像

csvfile = "summary.csv"
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for f in sys.argv[1:]:
        words = re.findall('\w+', open('f').read().lower())
        cnt1, cnt2 = 0, 0
        cntWords = len(words)
        for word in words:
            if word in wanted1:
                cnt1 += 1
            if word in wanted2:
                cnt2 += 1
        print cnt1, cnt2, cntWords
        res = [cnt1, cnt2, cntWords]
        writer.writerow(res)

PS請參閱計數器使用示例

暫無
暫無

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

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