Python文件I / O问题:绕过For循环?

时间:2016-08-03 04:05:16

标签: python io

def findWord(word):
    f = open("words.txt", "r")
    given_line = f.readlines()
    for line in f:
        if str(word) in line:
            part = line[0]
            ## print(line+"\n"+str(word)+" is a "+part)
            return True
        else:
            return False
    print("fail")
    f.close()

def partSpeech(inX):
    f = open("words.txt", "a")
    inX = inX.split()
    for i in inX:
        i = i.lower()
        if(findWord(i) == False):
            if "ify" in i[-3:] or "ate" in i[-3:] or "ize" in i[-3:] or "ing" in i[-3:] or "en" in i[-2:] or "ed" in i[-2:]:
                f.write("\nV"+i)
            elif "ment" in i[-4:] or "ion" in i[-3:] or "acy" in i[-3:] or "ism" in i[-3:] or "ist" in i[-3:] or "ness" in i[-3:] or "ity" in i[-3:] or "or" in i[-2:] or "y" in i[-1:]:
                f.write("\nN"+i)
            elif "ly" in i[-2:]:
                f.write("\nD"+i)
        else:
            print(i+" was already in the database.")

基本上,我对上述问题发生在"对于f:"中的行。问题是,在整个代码中放入了许多标记(打印以确定它在哪里获得)后,for循环甚至都没有运行!我不明白,不管它是否仅仅是那条线或f不被计算或是什么,但是。

目标是,在这个片段中,取出一堆词,将它们循环通过一个系统,检查它们是否已经存在于给定的文本文件中(我之所以遇到问题的部分) )然后,如果他们不这样做,请附加一个词性标记。

编辑:我根本没有收到任何错误,只是因为它没有按照应有的方式运行For循环。每个函数都会在某个时刻被调用,partSpeech会被一个小的单词列表调用到最后。

编辑2:进展!有点。文本文件为空,因此无法读取任何行。但是,现在它没有考虑这些词是否已经存在。它只是跳过它们。

2 个答案:

答案 0 :(得分:0)

首先,删除此行:

given_line

这是将文件的内容读入未使用的f变量,并将for放在文件的末尾。因此,findWord()循环无需循环。

您的def findWord(word): # it seems odd to pass a "word" parameter that isn't a str, but if you must handle that # case you only need to do the cast once word = str(word) # always use the with statement to handle resources like files # see https://www.python.org/dev/peps/pep-0343/ with open("words.txt", "r") as f: for line in f: if word in line: return True return False # only return False after the loop; once we've looked at every line # no need to call f.close(), the with statement does it for us 函数正在执行许多奇怪/有问题的事情,其中​​任何一个都可能导致您假设的行为意味着for循环甚至无法运行。这是一个可能的重新实施:

{{1}}

答案 1 :(得分:0)

for line in f:永远不会运行,因为您已经读取了文件内容并且光标位于文件的末尾。

你应该这样做:

for line in given_line:

或者您可以在for循环之前放置此语句:

f.seek(0)

将光标放回文件的开头。