【问题标题】:Text-file class python [duplicate]文本文件类python [重复]
【发布时间】:2014-07-31 20:45:24
【问题描述】:

这是我正在解决的问题:

开发一个 Textfile 类,提供分析文本文件的方法。 Textfile 类将支持将文件名(作为字符串)作为输入并实例化与相应文本文件关联的 Textfile 对象的构造函数。文本文件应支持分别返回字符数、单词数和行数的方法 nchars()、nwords() 和 nlines()。

这是我对这个问题的尝试:

class Textfile():
    def __init__(self, filename):
        self.file = open(filename)

    def nchars(self):
        return len(self.file.read())

    def nwords(self):
        content = self.file.read()
        words = content.split()
        return len(words)

   def nlines(self):
        content = self.file.read()
        return content.count('\n')

我所有的方法似乎都有效。但是,当我连续运行两种方法时,没有为第二种方法保存文本文件,我得到 0。

例如,
让 example.txt = 这是一个句子。

当我运行程序时,我应该得到这个

>>>>x = Textfile('example.txt')
>>>>x.nchars()
>>>>19
>>>>x.nwords()
>>>>4 
>>>>x.nlines()
>>>>1

不过,我明白了

>>>>x = Textfile('example.txt')
>>>>x.nchars()
>>>>19
>>>>x.nwords()
>>>>0 
>>>>x.nlines()
>>>>0

或者这个:

>>>>x = Textfile('example.txt')
>>>>x.nwords()
>>>>4
>>>>x.nchars()
>>>>0 
>>>>x.nlines()
>>>>0

如您所见,这些方法单独工作,但文本文件未保存在下一个方法中。

我做错了什么?

【问题讨论】:

  • .read() 文件之后,“读取头”位于末尾。 .seek(0)“倒带”。或者,计数并将所有值存储在 __init__ 中,然后您甚至不需要保持文件打开。
  • 您需要在每个方法中read 后回退文件。尝试使用 self.file.seek(0,0)。
  • @jonrsharpe 这看起来像是我的答案。

标签: python class text-files


【解决方案1】:

这是因为read() 函数只遍历一个文件一次。当您阅读时,它会移动到文件缓冲区中的位置。在你的函数中,你到达了文件的末尾。您需要关闭并重新打开文件才能执行您正在执行的操作。我建议将您的 init 函数重新设置为:

def __init__(self, filename):
    with open(filename, 'r') as inputfile:
        self.content = inputfile.read() 

然后在任何地方使用内容而不是阅读。如果您的程序由于意外丢失文件句柄而崩溃,它将提供可重用性和安全性。

正如@chepner 所说,编辑__init__ 以包含长度和计数(和其他)属性可能也是更好的做法,这样内容本身就不必保存在内存中。这看起来像

def __init__(self, filename):
    with open(filename, 'r') as inputfile:
        content = inputfile.read() 
    self.nChars = len(content)
    self.nLines = content.count('\n')
    self.nWords = len(content.split())

【讨论】:

  • 鉴于从磁盘读取可能比处理结果数据慢得多,您不妨预先计算 __init__ 中的计数并简单地从每个函数返回适当的结果,而不是保留内存中的文件内容。
猜你喜欢
  • 1970-01-01
  • 2018-02-02
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多