[英]How to create a word list made up of the words from file
我正在為文字游戲創建一個函數,我需要創建一個由名為 wordlist.txt 的文件中的單詞組成的單詞列表。 我的第一個想法是首先打開該文件並將打開的文件作為參數傳遞給我正在嘗試創建的函數。 但最后我意識到我的功能應該返回一個所有單詞的列表,其中的換行符從打開的文件 words_file 中刪除。(這在 python 中甚至可能?)。 在其他每一行文件的每一行都包含一個來自標准英文字母表的大寫字符的單詞,但我想我是通過使用 upper() 和 .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
,然后嘗試對不存在的參數調用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")
,它將返回列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.