如何创建由文件中的单词组成的单词列表

How to create a word list made up of the words from file

我正在为文字游戏创建一个函数,我需要创建一个由名为 wordlist.txt 的文件中的单词组成的单词列表。我的第一个想法是首先打开该文件并将打开的文件作为参数传递给我要创建的函数。但最后我意识到我的功能应该是 return 从打开的文件 words_file 中删除换行符的所有单词的列表。(在 python 中甚至可能吗?)。在其他文件的每一行中,文件的每一行都包含一个来自标准英语字母表的大写字符单词,但我想我是通过使用 upper() and.split() 得到的。 我非常坚持这一点。任何帮助都会有用。非常感谢你提前。 PS: 我发现这个结构在寻找关于这种读取​​文件的任何信息。 words_file = askopenfile(mode='r', title='Select word list file') 无论如何在这种情况下有用吗?

这是我的函数结构:

def read_words(words_file):

    """ (file open for reading) -> list of str

    Return a list of all words (with newlines removed) from open file
    words_file.

    Precondition: Each line of the file contains a word in uppercase characters
    from the standard English alphabet.
    """
    file = open("C:\Python34\wordlist.txt", "r")
    return words_file.read(wordlilst.txt).replace("\n", "").upper().split()

我假设您想使用参数 words_file 作为文件的来源。您的代码会忽略它,将硬编码文件分配给 file,然后尝试在 non-existing 参数上调用 read。 我认为这可能是您想要的:

def read_words(words_file):
words_list = [] # initialize empty word list
with open(words_file) as file: # open the file specified in parameter
                               # 'with' makes sure to close it again
    for line in file:          # iterate over lines
        words_list.append(line.replace("\n", "")) # add every line to list
                                 # ^ remove trailing newline, which iterating includes
return words_list # return completed list

要 运行 将其用于您的文件,请使用 read_words("C:\Python34\wordlist.txt"),这将 return 列表。