【问题标题】:Cleaning text for multiple files in Python在 Python 中清理多个文件的文本
【发布时间】:2018-05-19 16:30:11
【问题描述】:

我正在编写一个脚本来清理一个 .txt 文件,创建一个列表,计算唯一词的频率,并输出一个带有频率的 .csv 文件。我想打开多个文件并将它们组合起来仍然输出一个 .csv 文件。

首先编写将跨 .txt 文件的文本合并的代码,还是读取/清理所有唯一文件并随后合并列表/字典会更有效吗?最佳方案的语法是什么样的?

我一直在尝试自己研究它,但编码技能非常有限,似乎无法找到适合我特定问题的答案。我感谢任何和所有输入。谢谢!

import re

filename = 'testtext.txt'
file = open(filename, 'rt')
text = file.read()
file.close()

import re
words = re.split(r'\W+', text)

words = [word.lower() for word in words]

import string
table = str.maketrans('', '', string.punctuation)
stripped = [w.translate(table) for w in words]

from collections import Counter

countlist = Counter(stripped)

import csv

w = csv.writer(open("testtext.csv", "w"))
for key, val in countlist.items():
    w.writerow([key, val])

【问题讨论】:

  • 在您真正理解原因之前,您不需要最佳方案。使用任何合适的方法。

标签: python csv text


【解决方案1】:

如果您想计算多个文件的单词频率并将其输出到一个 CSV 文件中,您不需要对代码做太多操作,只需在代码中添加一个循环,例如:

import re
import string
from collections import Counter
import csv

files = ['testtext.txt', 'testtext2.txt', 'testtext3']
stripped = []

for filename in files:
    file = open(filename, 'rt')
    text = file.read()
    file.close()

    words = re.split(r'\W+', text)

    words = [word.lower() for word in words]

    table = str.maketrans('', '', string.punctuation)
    stripped += [w.translate(table) for w in words]  # concatenating parsed data

countlist = Counter(stripped)

w = csv.writer(open("testtext.csv", "w"))
for key, val in countlist.items():
    w.writerow([key, val])

我不知道这是否是最好的方法。
这将取决于以下因素:文件有多大?你想解析多少个文件?以及您希望多久解析一次x 大小的y 文件?等等等等
弄清楚这一点后,您就可以开始考虑优化流程的方法了。

【讨论】:

  • @SarahSteinhauer 不客气。如果问题已得到解答,请随时接受答案。
【解决方案2】:

如果需要计算频率,最好先将多个.txt文件中的字符串组合起来,要知道性能,可以在处理开始和结束时编写datetime函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2021-12-24
    • 2021-12-11
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多