2011-01-21 23 views
1

我想爲文字遊戲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'字都應該被刪除。

我也很感激,如果有人能讓我知道一個更有效的方式做這個,然後做一個巨大的初始名單。

+0

對此不起作用 – Falmarri

+0

應該發生什麼:想象一下,列表中包含以「a」開頭的所有單詞。用戶然後選擇字母'b'。目標單詞的起始字母爲'ab'。應該發生的情況是,列表中沒有直接跟着'b'的所有'a'單詞應該被刪除。 – Parseltongue

+0

當你迭代它時,你不能從列表中刪除東西。 「巨大的」?如果它只是很大,在每個字母后面添加一個新的列表,如果它真的很大,請使用數據庫,例如sqlite。 –

回答

2

我建議不要從您的列表中刪除單詞。它會非常緩慢,因爲在列表中間刪除的是O(N)。

最好只是創建一個新列表。一種可能的方式做,這是

wordlist = [w for w in wordlist if w.startswith(word)] 
+0

這正是我所需要的;謝謝 – Parseltongue

+0

有沒有辦法壓縮任何(我是Python的新手,所以我想學習如何儘可能高效和pythonic) – Parseltongue

+0

另外,什麼是一個簡單的方法來刪除所有包含較小單詞的單詞?例如,「蹩腳」這個詞應該是無法播放的,因爲它包含了「廢話」 – Parseltongue

1

彼得·諾維格有很大的討論,自動更正功能在這裏:

http://norvig.com/spell-correct.html

大名單的理解和上下文匹配顯得恰當 - 在21行這是一個快速閱讀(具有很好的解釋如下)。還可以查看python(IBM)的函數式編程的「Charming python」3部分。您可以使用一些列表解析來完成所有設置。

0

更換線路

for line in wordlist: 
    if not line.startswith(word): 
     wordlist.remove(line) 

如果你想爲ITA工作,你會更好的CLISP ...或Clojure的寫這個。