2017-04-26 9 views
-4

私はCharCounterという名前のイテレータクラスを実装しようとしています。このクラスはテキストファイルを開き、ユーザーが指定した文字数を含むテキストファイルから単語を返すイテレータを提供します。 1行に1語ずつ出力します。それは何をしているのではない、それはリストとして単語を出力しているし、それからそれは継続的に '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

公開されたコードは、ファイルの読み取りに関する質問がない限り、ファイルを読み取るべきではありません。結果を複製して検証することはできません。 (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 
関連する問題