文件读取和变量赋值

File Reading and Variable Assignments

所以我正在尝试制作一个游戏,其中 'GameMaster' 从 .txt 文件中选择第一个单词,然后用户尝试猜测这个单词。一旦用户正确猜出单词,GameMaster 就会查看文件中的下一行,用户必须再次猜测,依此类推...

我遇到的问题是让程序在游戏继续时分配变量。该程序应该反复查找,直到没有更多的单词可供选择,无论是 2 还是无穷大。

由于我在 python 中没有太多的文件交互经验,我最好的例子是这样的:

文件 "input.txt" 将包含:



老鼠
鼠标

我正在查看 .txt 文件中的内容:

def file_read():
with open ('/Users/someone/Desktop/input.txt', 'r') as myfile:
    data = myfile.read()
    for line in data:
        line.rstrip()
return data

您的函数 return 是文件的全部内容,未更改。 myfile.read() returns 文件中的字符串形式的数据。然后 for 循环遍历该字符串中的每个 字符 ,而不是行。此外,rstrip() 仅对每个字符进行操作。它不会影响 data 的内容,因为 data 是一个不可变的字符串,并且 rstrip() 的 return 值不会存储在任何地方。

这样的东西更适合:

def file_read():
    with open('/Users/someone/Desktop/input.txt') as myfile:
        return [line.rstrip() for line in myfile]

这将return 列出 文件中的剥离行。然后,您的单词猜测代码将遍历列表。

上面的方法可行,但是,如果输入文件很大,则效率不是很高,因为所有文件都将被读入内存以构建列表。更好的方法是使用一次生成一条剥离线的生成器:

def file_read():
    with open('/Users/someone/Desktop/input.txt') as myfile:
        for line in myfile:
            yield line.rstrip()

既然功能如此简单,那么费心费力似乎也无济于事。您的代码可以简单地是:

with open('/Users/someone/Desktop/input.txt') as myfile:
    for line in myfile:
        user_guess_word(line.rstrip())

其中 user_guess_word() 是一个与用户交互以猜测单词是什么的函数,一旦猜对了 returns。

这种方式使用readlines逐行获取list中的文件内容。 readlines returns 包含行的 list

现在遍历 list 以检查用户输入是否与行内容匹配(在本例中是一个词)。

with open ('/Users/someone/Desktop/input.txt', 'r') as myfile:
    words = myfile.readlines()
    while x < len(words):
        if words[x] == input('Enter word to guess'):
            print('Predicted word correctly')
        else:
            print('Wrong word. Try again')
            x -= 1
        x += 1

你可以这样做,

def fun():
    data = open('filename', 'r').readlines()
    user_guess, i = None, 0
    while i < len(data):
        user_guess = input()
        if user_guess not None and user_guess == data[i]:
            i = i + 1

在比较 user_guess 和 data[i]

时也请 trim() / strip()