Pygame在2.txt文件和用户inpu之间寻找匹配项

2024-09-29 23:27:13 发布

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

对于我的程序,我有两个.txt文件:一个是拼写正确的单词(wordscorect.txt),另一个是拼写相同的单词,在同一行,但拼写有误。其中一个拼错的单词被随机选取并显示在屏幕上。用户必须输入该单词的正确版本

我试着编写一些代码来比较.txt文件中的单词,但无法确定如何检查用户输入是否与正确的单词匹配,而正确的单词又与屏幕上随机选取的单词匹配。对不起,如果这是很糟糕的解释,但任何帮助都太好了!p>

   while word_pick == True:
        for event in pg.event.get():
            file1 = open("words.txt","r")
            file2 = open("wordsCorrect.txt","r")
            with file1 and file2:
                same = set(file1).intersection(file2)

Tags: 文件代码用户程序版本txtevent屏幕
1条回答
网友
1楼 · 发布于 2024-09-29 23:27:13

不要打开并读取事件循环中的文件,否则每次将事件添加到队列时,都会一次又一次地读取文件,例如,如果移动鼠标或按键

我建议将正确的单词和拼写错误的单词一起存储在一个文件中(可能是一个csv文件),创建一个字典,打开文件并添加拼写错误的单词作为键,添加正确的单词作为值

words = {}

with open('words.txt') as f:
    for line in f:
        misspelled, correct = line.strip().split(',')  # Comma as word separator.
        words[misspelled] = correct

然后可以通过以下方式检查用户输入是否正确:

current_word = 'bred'
user_input = 'bread'
if words[current_word] == user_input:
    print('Correct answer.')

或者,可以使用^{}函数将两个文件中的单词压缩到一起。这更容易出错,因为文件可能有不同的行号

with open('misspelled.txt') as f1, open('correct_words.txt') as f2:
    for misspelled, correct in zip(f1, f2):
        misspelled = misspelled.strip()
        correct = correct.strip()
        words[misspelled] = correct

相关问题 更多 >

    热门问题