0

下面是一个简单的搜索。它可以工作,除了iterator跳过文件的第一行。内部iterator第一个print语句有正确的单词,但第二个print语句(for循环之后)有第二行文本,而不是第一行。

for我错过了这个循环行为怎么办?

"""Searches for the query inside a file
"""
def lines(the_file, query):
    lines = open(the_file)
    line(lines, query)

def line(lines, query):
    line = lines.readline()
    iterator(line, lines, word, query)

def word(line, query):
    word = line.strip()
    conditional(query, word)

def iterator(this, that, function, query):
    print this
    for this in that:
        print this
        function(this, query)

def conditional(this, that):
    if this in that:
        output(that, True)
    else:
        None

def output(query, result):
    print query

def search(the_file, query):
    lines(the_file, query)

search('c:/py/myfile.txt', 'a')
4

2 回答 2

1

变量lines是一个文件对象,当您创建 a 时,readline()您将指针移动到第二行。

于 2013-01-29T23:44:47.857 回答
1

我认为你的问题在这里:

def line(lines, query):
    line = lines.readline()
    iterator(line, lines, word, query)

这一行:line = lines.readline()在开始迭代之前从文件中读取一行。然后在您的for循环中,您实际上是在覆盖this变量,它不再指向您的原始变量line

于 2013-01-29T23:45:38.297 回答