【发布时间】:2011-06-13 11:13:48
【问题描述】:
我想为文字游戏Ghost 创建计算机。但是,我在思考一个处理访问庞大单词列表的好方法时遇到了问题。这是我当前的实现(不起作用):
import os, random, sys, math, string
def main():
#Contains a huge wordlist-- opened up for reading
dictionary = open("wordlist.txt", "r")
wordlist = []
win= 0
turn= 0
firstrun = 0
word = ""
#while nobody has won the game
while win==0:
if turn == 0:
#get first letter from input
foo = raw_input("Choose a letter: ")[0]
word+=foo
print "**Current word**: "+ word
#Computer's turn
turn = 1
if turn == 1:
#During the first run the program gets all definitively
#winning words (words that have odd-number lengths)
#from the "dictionary" file and puts them in a list
if firstrun== 0:
for line in dictionary:
#if the line in the dictionary starts with the current
#word and has an odd-number of letters
if str(line).startswith(word) and len(line)%2 == 0:
wordlist.append(line[0: len(line)-1])
print "first run complete... size = "+str(len(wordlist))
firstrun = 1
else: #This is run after the second computer move
for line in wordlist:
#THIS DOES NOT WORK-- THIS IS THE PROBLEM.
#I want it to remove from the list every single
#word that does not conform to the current limitations
#of the "word" variable.
if not line.startswith(word):
wordlist.remove(line)
print "removal complete... size = "+str(len(wordlist))
turn = 0
if __name__ == "__main__":
main()
我已经在代码中划定了问题区域。我不知道为什么它不起作用。应该发生什么:想象一下列表中填充了所有以“a”开头的单词。然后用户选择字母“b”。然后目标词必须具有开头字母“ab”。应该发生的是,列表中所有不直接跟在“b”后面的“a”单词都应该被删除。
如果有人可以让我知道一种更有效的方法,然后制作一个庞大的初始列表,我也将不胜感激。
【问题讨论】:
-
应该发生什么:想象一下列表中填充了所有以“a”开头的单词。然后用户选择字母“b”。目标词则具有开头字母“ab”。应该发生的是,列表中所有不直接跟在“b”后面的“a”单词都应该被删除。
-
您不能在迭代列表时从列表中删除内容。 “巨大”有多大?如果它只是很大,请在每个字母后制作一个新列表。如果真的很大,请使用数据库,例如 sqlite。