[英]Problem with using a text file to create a dictionary that has word length as its key and the actual word itself as the value in Python
I'm currently a beginner in Python taking an introductory course for Python and I'm having trouble with creating a hangman game in which we derive our words from a text file that has each word printed on a new line, where we then in a function choose a word at random based on the word length indicated by the user.我目前是 Python 的初学者,正在参加 Python 的入门课程,我在创建一个刽子手游戏时遇到了麻烦,在该游戏中,我们从一个文本文件中导出我们的单词,每个单词都打印在一个新行上,然后我们在function 根据用户指定的字长随机选择一个字。 I'm not sure how we are supposed to do that, I've uploaded my current code, the problem is when I print out the dictionary only the words from the text file actually get printed out, I'm not sure why the dictionary with the keys and values aren't getting printed out... I'm also not sure why my professor wants us to use a try and except in this function and how I'm supposed to use max_size.
我不确定我们应该怎么做,我已经上传了我当前的代码,问题是当我打印出字典时,只有文本文件中的单词实际被打印出来,我不确定为什么字典键和值没有被打印出来......我也不确定为什么我的教授希望我们尝试一下,除了这个 function 以及我应该如何使用 max_size。
Here's what I've currently done这是我目前所做的
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
The function I'm using to print out我用来打印的 function
def print_dictionary (dictionary):
max_size = 12
with open('dictionary.txt', 'r') as dictionary:
print(dictionary.read())
Try the following:尝试以下操作:
def import_dictionary(dictionary_file):
dictionary = {}
max_size = 12
with open(dictionary_file, 'r') as f:
words = f.read().split('\n') # each word is on new line so split on newline: '\n'
for word in words:
length = len(word)
if length > max_size: # If word too long, ignore it
continue
elif dictionary.get(length) is not None:
dictionary[length].append(word) # If dict already has entry for word length, append word.
else:
dictionary[length] = [word] # Otherwise create entry
return dictionary
Try this.尝试这个。
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.