Python- 单词游戏“鬼”,文件I/O和列表问题
我想为一个文字游戏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'开头。应该做的是,列表中所有以'a'开头但后面没有直接跟着'b'的单词都应该被删除。
如果有人能告诉我一个更有效的方法,而不是一开始就创建一个巨大的列表,我会非常感激。
相关问题:
3 个回答
0
如果你想为ITA工作,最好用clisp或者clojure来写这个。
1
彼得·诺维格在这里对自动纠错进行了很好的讨论:
http://norvig.com/spell-correct.html
里面提到的大型列表推导和上下文匹配看起来很相关,而且只有21行,读起来很快(后面还有很好的解释)。另外,看看“迷人的Python”这三部分关于用Python进行函数式编程的内容(IBM)。你可以用几个列表推导来完成所有的设置。
2
我建议你不要从你的列表中删除单词。因为在列表中间删除单词会非常慢,这个过程的复杂度是O(N),也就是说,随着列表变长,删除的速度会变得越来越慢。
更好的方法是直接创建一个新的列表。你可以用下面的方式来替换原来的代码:
for line in wordlist:
if not line.startswith(word):
wordlist.remove(line)
用
wordlist = [w for w in wordlist if w.startswith(word)]