2017-04-26 100 views
-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 
+1

请改用https://codereview.stackexchange.com/。我怀疑有人会帮助你。 – hspandher

+0

那么你的代码有什么问题 – depperm

+2

“修复”和“改善”是非常不同的。 “修复”意味着“修复不起作用的代码”,或者“使错误的代码正常工作”,但“改进”是“使得工作正常,代码工作更好”。 – ForceBru

回答

0

张贴在SO上的代码不应读取文件,除非问题是关于读取文件。结果不能被复制和验证。 (请参阅MCVE。)相反,请将文本字符串定义为文件的替代品。

您的代码打印长度为n的单词作为列表,因为这是您要求它与print(pwords)一起完成的操作。它重复打印文件名的第一个字符,因为这就是您要求它在__next__方法中执行的操作。

您的班级__init__确实比您描述的要多。试图从文字中去掉标点符号并不会做任何事情。下面的代码定义了一个将文本转换为剥离单词列表的类(带有重复项)。它还定义了一个过滤单词列表的参数化生成器方法。

class Words: 
    def __init__(self, text): 
     self.words = words = [] 
     for line in text.split('\n'): 
      for word in line.split(): 
       words.append(word.strip(""",'."?!()[]{}*$#""")) 
    def iter_n(self, n): 
     for word in self.words: 
      if len(word) == n: 
       yield word 

# Test 
text = """ 
It should output a word per line. 
Which is not what's it's doing! 
(It outputs the words as a [list] and then continuously outputs 'a'.) 
How can I fix my #*!code? 
""" 
words = Words(text) 
for word in words.iter_n(5): 
    print(word) 

# Prints 
Which 
doing 
words