简体   繁体   English

使用文本文件创建字典时出现问题,该字典以字长为键,实际字本身为 Python 中的值

[英]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.

相关问题 python递归:使用单词的键值字典创建一定长度的所有可能句子 - python recursion: create all possible sentence of certain length using a key-value dictionary of word 循环浏览文本文件,同时将其添加到字典中,以单词长度为键 - Looping through a text file, while adding it to a dictionary, with word length as the key 从文本文件创建Python字典并检索每个单词的计数 - Create Python Dictionary from text file and retrieve count of each word 使用python用值替换文本文件中的单词 - Replacing a word in a text file with a value using python 来自文本文件的Python字长计数 - Python word length count from a text file 检查文本中的单词,如果它与字典键匹配,则添加到该键的值 - checking a word in a text and if it matched a dictionary key add to the value of that key 读取具有键值对的文本文件,并使用python pandas将每一行转换为一个字典 - read a text file which has key value pairs and convert each line as one dictionary using python pandas 读取文本文件,然后将第一个和第三个单词分别作为键和值存储在字典中 - Reading a text file then storing first and third word as key and value respectively in a dictionary 如何使用python docx获取word文档中文本的实际样式 - How to get actual style of text in word document using python docx 在 Python 中按字长拆分文本 - Split a text by word length in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM