私は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
代わりにhttps://codereview.stackexchange.com/をお試しください。私は誰もあなたをここで助けることを疑う。 – hspandher
よくあるご質問 – depperm
「修正」と「改善」は大きく異なります。 「修正する」とは「機能しないコードを修復する」または「間違ったコードが正しく機能するようにする」ことを意味しますが、「改善する」とは「既に正しく機能しています。 – ForceBru