计算多个文件(文本)中的两个值(总单词和唯一值),并在Python中输出csv



我处理各种文本文件集合,我想了解这些文件的各种信息,比如字数等。我有成功做到这一点的代码,现在我想在我的工作流程中引入一个脚本,该脚本将通过目录工作,并编译其中文本文件的统计信息。

这是我的草稿:

#! /usr/bin/env python
# Get from each text file a total word count and a unique word count.
# Output a CSV with three columns: filename, total, unique.
import glob
with open (file_name) as f, open ('countfile.csv', 'w') as out :
    list_of_files = glob.glob('./*.txt)
    for file_name in list_of_files:
        ???
        out.write('{f},{t},{u}n'.format(f =file_name, t =word_total, u =uniques)

上面的问号是我想对每个文件做什么的占位符,这就是下面的代码:

# Total No. of Words        
word_list = re.split('s+', textfile.read().lower())
word_total = len(word_list)
# Unique Words
freq_dic = {}
punctuation = re.compile(r'[.?!,":;]') 
for word in word_list:
    # remove punctuation marks
    word = punctuation.sub("", word)
    # form dictionary
    try: 
        freq_dic[word] += 1
    except: 
        freq_dic[word] = 1
uniques = len(freq_dic)

我不太知道如何将所有这些代码插入到上面的代码中。不知怎么的,我怀疑这不会奏效,但我不知道如何继续。如有任何帮助,我们将不胜感激。如果我能弄清楚这一点,那么我想我可能真的能够自动化很多事情。

我知道第二块代码可能不是最漂亮的,但它几乎是我能得到的最紧凑的,并且仍然理解它在做什么。毫无疑问,我对Python的学习还处于早期阶段。

编辑澄清:

我有一个文本目录:

text1.txt  
text2.txt  
text3.txt  

我想要的是把这个脚本指向那个目录,让它遍历所有文本,并输出一个CSV文件,格式如下:

text1, 345, 123
text2, 1025, 318
text3, 765, 245

(注意,没有必要去掉文件名的.txt。(

files = {}
for fpath in glob.glob("*.txt"):
    with open(fpath) as f:
         fixed_text = re.sub("[^a-zA-Z'-]"," ",f.read())
    words = fixed_text.split()
    total_words = len(words)
    total_unique = len(set(words))
    files[fpath] = (total_words, total_unique)
    print "Total words:", total_words
    print "Total unique:", total_unique
with open("some_csv.csv", "w") as f:
    for fname in files:
        print >> f, "%s,%s,%s" % (fname, files[fname][0], files[fname][1])

我认为这应该有效。。。

最新更新