gpt4 book ai didi

python - Python中多种方式读取文件

转载 作者:行者123 更新时间:2023-11-30 23:06:22 25 4
gpt4 key购买 nike

我正在尝试建立一个系统来对文本文件运行各种统计信息。在这项工作中,我需要在 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 ?

最佳答案

data.read() 的调用将文件指针放置在文件末尾,因此此时您无需再读取任何内容。您必须关闭并重新打开文件,或者更简单地使用 data.seek(0)

在开头重置指针

关于python - Python中多种方式读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32698099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com