首页 > 解决方案 > 使用文本文件创建字典时出现问题,该字典以单词长度为键,而实际单词本身为 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())

标签: pythonfiledictionary

解决方案


尝试这个 。

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])

推荐阅读