[英]Iterating through a text file using a for loop in python - why does this work?
我目前正在学习如何在 Python 中创建拼写检查器。 在一些教程中,我看到如下内容:
def ReadDictionaryFile(dictionaryfilename):
dictionarywords = [] # stores words in a list
inputfile = open(dictionaryfilename, "r")
for line in inputfile: # iterate over the lines of the file
word = line.strip() # whitespace removed
dictionarywords.append(word) # appends word to the list
inputfile.close()
return dictionarywords
但我不明白 python 是如何知道将它分成几行的。
在for line in inputfile:
,"line" 只是一个变量,那么代码的哪一部分实际上告诉它在 \\n 处停止?
python 中是否有一些内置功能,其中 for 循环遍历文本只是在遇到 \\n 时开始下一次迭代? 我找不到这方面的任何信息...
任何帮助表示赞赏!
这是有效的,因为open
返回的文件对象在其特殊的“dunder”(双下划线) __iter__
方法中实现了该行为。 这是在for
循环中隐式迭代对象时调用的方法。
例如,考虑以下代码:
class LineIterator:
def __init__(self, contents):
self.contents = contents
def __iter__(self):
yield from self.contents.splitlines()
it = LineIterator("""Hello
Foobar
Goodbye""")
for line in it:
print("The line was", repr(line))
这打印出来
The line was 'Hello'
The line was 'Foobar'
The line was 'Goodbye'
该for
循环完全等同于显式版本:
for line in iter(it):
print("The line was", repr(line))
或者真正明确的版本:
for line in it.__iter__():
print("The line was", repr(line))
原始版本以及使用iter(it)
,只需调用__iter__
方法。 标准库广泛使用此模式,您可以在自己的代码中使用它来使对象按需要运行。
( yield from x
的yield from x
基本上意味着“将每个元素 x 传递给循环”。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.