![](/img/trans.png)
[英]python recursion: create all possible sentence of certain length using a key-value dictionary of word
[英]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
我目前是 Python 的初學者,正在參加 Python 的入門課程,我在創建一個劊子手游戲時遇到了麻煩,在該游戲中,我們從一個文本文件中導出我們的單詞,每個單詞都打印在一個新行上,然后我們在function 根據用戶指定的字長隨機選擇一個字。 我不確定我們應該怎么做,我已經上傳了我當前的代碼,問題是當我打印出字典時,只有文本文件中的單詞實際被打印出來,我不確定為什么字典鍵和值沒有被打印出來......我也不確定為什么我的教授希望我們嘗試一下,除了這個 function 以及我應該如何使用 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
我用來打印的 function
def print_dictionary (dictionary):
max_size = 12
with open('dictionary.txt', 'r') as dictionary:
print(dictionary.read())
嘗試以下操作:
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
嘗試這個。
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.