本文介绍了按字长索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是简单地做一个hang子游戏。但是,我已经有点过于雄心勃勃了。我想要求用户输入他们想要多长时间。然后选择该长度的随机字。要索引整个字典的长度在每次迭代都需要太长时间。所以。我有一本格式如下的字典:



zymosans



zymoscope



zymoses



...



我希望能够输出一个文件每个字长自动使用此程序。像这样:



1letterwords.txt



2letterwords.txt



等等。



我昨天开始玩python ...我搜索了网站和这个网站,没有想到什么。
我想要一些关于如何从这个特定的编程问题开始的指针。
提前感谢!
(为了弄清楚,hangman游戏会在所请求的wordlength文件中打开一个随机行,相当显着地降低了性能影响。)

解决方案

获取随机文件行可能不是您想要做的任何事情,或者将它们保留在列表中,和/或dict应该是数百万字的。



您可以通过遍历所有单词并将其添加到列表种子defaultdict中来存储单词长度列表:

 从集合导入defaultdict 
导入随机

wordsByLength = defaultdict(列表)
所有词中的单词:
wordsByLength [len(word)]。 append(word)

然后每当你需要一个随机字,你可以做:

  randomLen = random.choice(wordsByLength.keys())
randomWord = random.choice(wordsByLength [randomLen])

或者您可以将randomLen替换为speci你想要的长度。


My aim was to simply make a hangman game. However, I have been slightly over-ambitious. I want to ask the user to input how long they want the word. Then choose a random word of that length. To index an entire dictionary of that length would take far too long on each iteration. So. I have a dictionary, formatted like so:

zymosans

zymoscope

zymoses

...

I would like to be able output a file for each 'length of word' automatically using this program. Like this:

1letterwords.txt

2letterwords.txt

and so forth.

I started python...yesterday. I searched both the web and this site and came up with nothing.I would like some pointers as to how to start with this specific programming problem.Thanks in advance!(To clarify, the hangman game would open a random line in the requested wordlength file, reducing performance impact...fairly dramatically.)

解决方案

Getting random lines of files is probably not what you want to do either ... keeping them in a list and/or dict should be fine even for millions of words.

you can store list of words by their length by iterating over all your words and adding them to a list seeded defaultdict:

from collections import defaultdict
import random

wordsByLength = defaultdict( list )
for word in allWords:
    wordsByLength[ len(word) ].append( word )

Then whenever you need a random word you can do:

randomLen = random.choice( wordsByLength.keys() )
randomWord = random.choice( wordsByLength[ randomLen ] )

Or you can replace randomLen with the specified length you wanted.

这篇关于按字长索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 18:07