-4
我想实现一个名为CharCounter的迭代器类。这个类打开一个文本文件并提供一个迭代器,该文件返回包含用户指定数量字符的文本文件中的单词。它应该每行输出一个字。不是它在做什么,而是将这些单词作为一个列表输出,然后不断输出'a'。我如何修复我的代码?修复Python代码
class CharCounter(object):
def __init__(self, fileNm, strlen):
self._fileNm = fileNm
self._strlen = strlen
fw = open(fileNm)
text = fw.read()
lines = text.split("\n")
words = []
pwords =[]
for each in lines:
words += each.split(" ")
chkEnd = ["'",'"',",",".",")","("]
if words[-1] in chkEnd:
words = words.rstrip()
for each in words:
if len(each) == strlen:
pwords.append(each)
print(pwords)
def __iter__(self):
return CharCounterIterator(self._fileNm)
class CharCounterIterator(object):
def __init__(self,fileNm):
self._fileNm = fileNm
self._index = 0
def __iter__(self):
return self
def next(self):
try:
ret = self._fileNm[self._index]
return ret
except IndexError:
raise StopIteration
if __name__=="__main__":
for word in CharCounter('agency.txt',11):
print "%s" %word
请改用https://codereview.stackexchange.com/。我怀疑有人会帮助你。 – hspandher
那么你的代码有什么问题 – depperm
“修复”和“改善”是非常不同的。 “修复”意味着“修复不起作用的代码”,或者“使错误的代码正常工作”,但“改进”是“使得工作正常,代码工作更好”。 – ForceBru