从特定的方式读取文件中的单词

2024-04-26 07:56:50 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试将一个单词存储到一个文件中(我已经设法找到了方法)。然后程序会重复并要求我输入另一个单词。它应该检查这个单词是否已经存在于文件中(它应该这样做)。我有它的点,我已经输入了一个字,它已经存储在文件中,但当我再次输入相同的字,它没有意识到这个字已经存在于文件中(这都在def函数中,所以当我说下一次循环时,我是指下一次调用函数时)

代码如下:

def define():
    testedWord = subject
    lineNumber = 1
    lineInFile = "empty"
    exists = False
    while lineInFile != "":
        wordsFile = open("Words.txt", "a")
        lineInFile = linecache.getline("Words.txt", lineNumber)
        lineNumber = lineNumber + 1
        lineInFile = lineInFile.replace("\n", "")
        if lineInFile == subject:
            definitionNumber = lineNumber
            exists = True
    if exists == False:
        wordsFile.write(testedWord)
        wordsFile.write("\n")
        wordsFile.close()

subject = input("")
define()
##This whole thing basically gets repeated

就像我说的,如果我存储了一个新词,然后在同一个程序中再次尝试输入同一个词,那么它就不会意识到它已经存储了这个词。当我停止程序并重新启动它时,它工作了(但我不想这样做)

谢谢你的帮助(如果有可能的话,哈哈) 丹


Tags: 文件程序txtfalsedefexists单词subject
1条回答
网友
1楼 · 发布于 2024-04-26 07:56:50

我认为你(几乎)把每件事都变得比它需要的复杂。这里有一种不同的方法来做你想做的事情:

def word_check(f_name, word):

    with open(f_name) as fi:
        for line in fi: # let Python deal with line iteration for you
            if line.startswith(word):
                return # return if the word exists

    # word didn't exist, so reopen the file in append mode
    with open(f_name, 'a') as fo:
        fo.write("{}\n".format(word))

    return

def main():

    f_name = "test.txt"

    with open(f_name, 'w') as fo:
        pass # just to create the empty file

    word_list = ['a', 'few', 'words', 'with', 'one',
                 'word', 'repeated', 'few'] # note that 'few' appears twice

    for word in word_list:
        word_check(f_name, word)

if __name__ == "__main__":
    main()

这将生成包含以下文本的输出文件:

a
few
words
with
one
repeated

在这个示例中,我只是创建了一个单词列表,而不是使用输入来保持示例的简单性。不过,请注意当前方法的效率有多低。你正在重新打开一个文件,读取输入的每一个单词的每一行。考虑在记忆中建立你的单词表,并在最后写出来。下面是一个利用内置set数据类型的实现。他们不允许重复的元素。如果您可以在程序运行的而不是在运行时写入文件,则可以这样做:

def main():

    word_set = set()

    while True:
        word = input("Please enter a word: ")

        if word == 'stop': # we're using the word 'stop' to break from the loop
            break          # this of course means that 'stop' should be entered 
                           # as an input word unless you want to exit
        word_set.add(word)

    with open('test.txt', 'w') as of:
        of.writelines("{}\n".format(word) for word in word_set)
        # google "generator expressions" if the previous line doesn't
        # make sense to you

    return

if __name__ == "__main__":
    main()

打印输出:

Please enter a word: apple
Please enter a word: grape
Please enter a word: cherry
Please enter a word: grape
Please enter a word: banana
Please enter a word: stop

生成此文件:

grape
banana
cherry
apple

相关问题 更多 >