我想爲文字遊戲Ghost創建計算機。但是,我在思考處理訪問巨大單詞列表的好方法時遇到問題。這是我目前的實施(不起作用):Python-文字遊戲「Ghost」,文件I/O和列表問題
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'字都應該被刪除。
我也很感激,如果有人能讓我知道一個更有效的方式做這個,然後做一個巨大的初始名單。
對此不起作用 – Falmarri
應該發生什麼:想象一下,列表中包含以「a」開頭的所有單詞。用戶然後選擇字母'b'。目標單詞的起始字母爲'ab'。應該發生的情況是,列表中沒有直接跟着'b'的所有'a'單詞應該被刪除。 – Parseltongue
當你迭代它時,你不能從列表中刪除東西。 「巨大的」?如果它只是很大,在每個字母后面添加一個新的列表,如果它真的很大,請使用數據庫,例如sqlite。 –