按词长索引
我想做一个简单的猜单词游戏(hangman)。不过,我有点想得太复杂了。我想让用户输入他们想要的单词长度,然后随机选择一个那个长度的单词。但是,如果每次都要查找整个字典,实在是太慢了。所以,我有一个字典,格式是这样的:
zymosans
zymoscope
zymoses
...
我希望这个程序能自动生成每个“单词长度”的文件。比如:
1letterwords.txt
2letterwords.txt
依此类推。
我昨天才开始学Python。我在网上和这个网站上搜索过,但没有找到相关的内容。 我希望能得到一些关于如何开始解决这个具体编程问题的建议。 提前谢谢大家! (为了说明,猜单词游戏会从请求的单词长度文件中随机打开一行,这样性能影响会小很多……)
4 个回答
0
例如:
url = urllib.urlopen('http://download.oracle.com/javase/tutorial/collections/interfaces/examples/dictionary.txt')
random.choice([item for item in url if len(item) == 8])
2
把整个字典加载到内存中其实没什么大不了的。你可以试试下面这个方法:
import random
from collections import defaultdict
# load words
index = defaultdict(list)
with open('words.txt') as file:
for line in file:
word = line.strip().lower()
index[len(word)].append(word)
# pick a random word
length = int(raw_input('Enter word length: '))
word = random.choice(index[length])
如果你还想按照单词长度生成不同的文件,可以在像上面那样加载完索引后运行下面的代码:
for length in sorted(index):
path = 'words%d.txt' % length
with open(path, 'w') as file:
for word in index[length]:
file.write('%s\n' % word)
1
从文件中随机获取几行内容可能不是你想要的做法……把它们放在一个列表或者字典里,即使是上百万个单词也没问题。
你可以通过遍历所有单词,把它们按照长度存储到一个默认字典中:
from collections import defaultdict
import random
wordsByLength = defaultdict( list )
for word in allWords:
wordsByLength[ len(word) ].append( word )
然后每当你需要一个随机单词的时候,你可以这样做:
randomLen = random.choice( wordsByLength.keys() )
randomWord = random.choice( wordsByLength[ randomLen ] )
或者你可以把randomLen替换成你想要的具体长度。