python - 使用文本文件创建字典时出现问题,该字典以单词长度为键,而实际单词本身为 Python 中的值
问题描述
我目前是 Python 的初学者,正在学习 Python 入门课程,我在创建一个刽子手游戏时遇到了麻烦,在该游戏中,我们从一个文本文件中派生出我们的单词,每个单词都打印在一个新行上,然后我们在一个函数根据用户指定的单词长度随机选择一个单词。我不确定我们应该怎么做,我已经上传了我当前的代码,问题是当我打印出字典时,只有文本文件中的单词实际被打印出来,我不确定为什么字典键和值没有被打印出来......我也不确定为什么我的教授希望我们在这个函数中使用 try 和 except 以及我应该如何使用 max_size。
这是我目前所做的
def import_dictionary (dictionary_file):
dictionary = {}
max_size = 12
with open ('dictionary.txt', 'a+') as dictionary:
dictionary_file = dictionary.read().split()
for word in dictionary_file:
dictionary[len(word)] = word
return dictionary
我用来打印的功能
def print_dictionary (dictionary):
max_size = 12
with open('dictionary.txt', 'r') as dictionary:
print(dictionary.read())
解决方案
尝试这个 。
from collections import defaultdict
import random
def read_text_file():
words = defaultdict(list)
with open("file.txt","r") as f:
text_file = f.read()
text_file = text_file.split("\n")
for wrd in text_file:
words[len(wrd)].append(wrd)
return words
def main():
user_length = int(input())
words = read_text_file()
shuffle_words = random.sample(words[user_length])
print(shuffle_words[0])
推荐阅读
- java - 不使用原始类型无法获取泛型类型的类对象
- php - laravel如何保护从刀片到控制器的数据传递
- javascript - 如何使用 javascript 将 json prettry 格式输出为 html?
- reactjs - 酶 / Jest 间谍未调用 onClick
- javascript - 为什么联系表电子邮件在某些字段中发送“值”而不是“名称”?
- chromium-embedded - 本地文件系统中带有 html/js 文件的 Cefpython 应用程序
- mongoose - 如何使用猫鼬创建更旧的负载或加载更多调用
- java - 防止按钮样式更改
- kubernetes - 访问 Oracle Cloud 中计算实例上的 Kubernetes 仪表板
- ionic-framework - 离子 3 navCtrl.setroot()