【问题标题】:Reading file multiple ways in Python在 Python 中以多种方式读取文件
【发布时间】: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', '')uncommentedcommented 时?
  • 我很抱歉,现在修正了错字。我的意思是,当我注释掉 string = ... 时,第二段代码将运行。

标签: python


【解决方案1】:

data.read() 的调用将文件指针放在文件末尾,因此此时您没有更多内容要阅读。您要么必须关闭并重新打开文件,要么更简单地在开始时使用 data.seek(0) 重置指针

【讨论】:

  • 感谢您,在第二段代码的顶部添加data.seek(0) 使其按预期运行。
【解决方案2】:

先看一行:

string = data.read().replace('\n', '')

您正在从数据中读取一次。现在,光标在数据的末尾。

然后看线,

for line in data:

你试图再读一遍,但你做不到,因为数据中没有其他内容,你在它的末尾。所以len(word_list)返回0。

你除以它并得到错误。

ZeroDivisionError:浮点除以零。

但是当你评论它时,现在你只阅读一次,这是有效的,所以你的代码的第二部分现在可以工作了。

现在清除吗?

那么,现在该怎么办?

data.read()之后使用data.seek()

演示:

>>> a = open('file.txt')
>>> a.read()
#output
>>>a.read()
#nothing
>>> a.seek(0)
>>> a.read()
#output again

【讨论】:

  • 非常好,我还是有点太习惯 PHP 中的这些操作,我会在之前将它存储为字符串。
【解决方案3】:

这是一个简单的解决方法。将for line in data: 行替换为:

data.seek(0)
for line in data.readlines():
  ...

它基本上指向文件的开头并逐行再次读取。

虽然这应该可行,但您可能希望简化代码并只读取一次文件。比如:

with open(file, "r") as fin:
  lines = fin.readlines()
  string = ''.join(lines).replace('\n', '')

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 2019-02-06
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多