修复Python代码
我试图实现一个名为CharCounter的迭代器类。此类打开一个文本文件并提供一个迭代器,该迭代器从包含用户指定字符数的文本文件返回单词。它应该每行输出一个字。这不是它在做什么,它把单词作为一个列表输出,然后连续输出“a”。如何修复我的代码修复Python代码,python,python-2.7,Python,Python 2.7,我试图实现一个名为CharCounter的迭代器类。此类打开一个文本文件并提供一个迭代器,该迭代器从包含用户指定字符数的文本文件返回单词。它应该每行输出一个字。这不是它在做什么,它把单词作为一个列表输出,然后连续输出“a”。如何修复我的代码 class CharCounter(object): def __init__(self, fileNm, strlen): self._fileNm = fileNm self._strlen = strlen
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
发布在SO上的代码不应该读取文件,除非问题是关于读取文件。结果无法复制和验证。看见而是将文本字符串定义为文件的替代项 您的代码将长度为n的单词打印为列表,因为这是您要求它对printpwords执行的操作。它会重复打印文件名的第一个字符,因为这是在uuu next_uuu方法中要求它执行的操作 你的类uuu init uuuu比你描述的要多。试图从单词中去掉标点符号没有任何作用。下面的代码定义了一个类,该类将文本转换为包含重复项的精简单词列表。它还定义了过滤单词列表的参数化生成器方法
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
试试看。我怀疑这里是否有人会帮你。你的代码修复和改进有什么不同。修复意味着修复不工作的代码,或者使错误代码正确工作,但改进意味着使已经工作的、正确的代码工作“更好”。@hspandher应该只在没有bug的情况下推荐该站点。由于OP状态修复/改进,这可能意味着它有一些bug和错误,这在codereview上是离题的。至于你的第二条评论,如果代码不起作用,OP编辑了他的问题,人们会帮助你。。。不管怎样,你的两个说法似乎都有点误导。@hspandher:在不确定它是否合适的情况下推荐另一个网站是危险的。这个问题很可能会就此结束,因为它似乎已经破坏了代码,并且没有描述。