如何在Python中从文本文件内的字典随机打印一个单词?
从文本文件的字典中随机打印单词的方法
首先要修正你的word_list.txt文件里的语法问题:字典的键(happy、apple等)需要加上引号(单引号或双引号均可),否则Python会把它们当作未定义的变量,无法正确解析。修正后的文件内容应该是这样:
words = { 'happy': "feeling or showing pleasure or contentment.", 'apple': "the round fruit which typically has thin green or red skin and crisp flesh.", 'today': "on or in the course of this present day.", 'faeces': "waste matter remaining after food has been digested, discharged from the bowels; excrement." }
接下来用Python实现随机打印单词的逻辑:
import random # 读取文件并加载字典 with open('word_list.txt', 'r', encoding='utf-8') as file: exec(file.read()) # 执行文件中的代码,将words字典加载到当前程序中 # 把字典的键转换成列表,再随机选一个 random_word = random.choice(list(words.keys())) # 打印随机选中的单词 print(random_word)
如果需要同时打印单词和对应的释义,可以把最后一行改成:
print(f"{random_word}: {words[random_word]}")
内容的提问来源于stack exchange,提问作者U Ein
相关产品推荐
相关产品推荐

