簡體   English   中英

Python:將目錄中的所有文件寫入一個cdv文件

[英]Python: Write all files in a directory to one cdv file

我正在嘗試創建一個文本集合的雙峰圖,這樣我就可以投影一個單詞或單詞一個文本的網絡。 我的一位同事表示,如果我可以將我的所有文件保存為以下格式的單個csv文件,則可以使用剩下的工作流程:

textfile1, words words words
textfile2, words words words

我寫了以下腳本:

#! /usr/bin/env python

# a script to convert all text files in a directory to the format:
# filename, words from file (no punctuation)

import glob
import re

files = {}
for fpath in glob.glob("*.txt"):
    with open(fpath) as f:
         just_words = re.sub("[^a-zA-Z'-]"," ",f.read())

with open("mastertext.csv", "w") as f:
    for fname in files:
        print >> f , "%s,%s"%(fname,just_words)

該腳本將運行並生成輸出文件,但是輸出文件為空白,並且我沒有收到錯誤響應-作為Python新手,這對我來說是很多學習的來源。 我在這里走的正確嗎?如果是,我想念的是什么?

您需要將just_words的數據保存到files 在這種情況下,我使用元組列表而不是字典,但是如果願意,您仍然可以使用字典。 :-)

files = []
for fpath in glob.glob("*.txt"):
    with open(fpath) as f:
        just_words = re.sub("[^a-zA-Z'-]"," ",f.read())
        files.append((fpath, just_words))

with open("mastertext.csv", "w") as f:
    for fname, just_words in files:
        print >> f , "%s,%s"%(fname,just_words)

暫無
暫無

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

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