【发布时间】: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