【发布时间】:2015-09-21 23:16:21
【问题描述】:
我正在尝试建立一个系统来运行文本文件的各种统计信息。在这项工作中,我需要在 Python (v2.7.10) 中打开一个文件并将其作为行和字符串读取,以便统计函数起作用。
到目前为止,我有这个:
import csv, json, re
from textstat.textstat import textstat
file = "Data/Test.txt"
data = open(file, "r")
string = data.read().replace('\n', '')
lines = 0
blanklines = 0
word_list = []
cf_dict = {}
word_dict = {}
punctuations = [",", ".", "!", "?", ";", ":"]
sentences = 0
这将设置文件和初步变量。此时,print textstat.syllable_count(string) 返回一个数字。此外,我有:
for line in data:
lines += 1
if line.startswith('\n'):
blanklines += 1
word_list.extend(line.split())
for char in line.lower():
cf_dict[char] = cf_dict.get(char, 0) + 1
for word in word_list:
lastchar = word[-1]
if lastchar in punctuations:
word = word.rstrip(lastchar)
word = word.lower()
word_dict[word] = word_dict.get(word, 0) + 1
for key in cf_dict.keys():
if key in '.!?':
sentences += cf_dict[key]
number_words = len(word_list)
num = float(number_words)
avg_wordsize = len(''.join([k*v for k, v in word_dict.items()]))/num
mcw = sorted([(v, k) for k, v in word_dict.items()], reverse=True)
print( "Total lines: %d" % lines )
print( "Blank lines: %d" % blanklines )
print( "Sentences: %d" % sentences )
print( "Words: %d" % number_words )
print('-' * 30)
print( "Average word length: %0.2f" % avg_wordsize )
print( "30 most common words: %s" % mcw[:30] )
但这失败了,因为 22 avg_wordsize = len(''.join([k*v for k, v in word_dict.items()]))/num 返回一个 ZeroDivisionError: float 除以零。但是,如果我从第一段代码中注释掉 string = data.read().replace('\n', ''),我可以毫无问题地运行第二段代码并获得预期的输出。
基本上,我该如何设置,以便我可以在data 上运行第二段代码,以及在string 上运行 textstat?
【问题讨论】:
-
第二部分何时运行?当
string = data.read().replace('\n', '')是uncommented或commented时? -
我很抱歉,现在修正了错字。我的意思是,当我注释掉
string = ...时,第二段代码将运行。
标签: python