2012-07-04 42 views
1

我目前正在爲RPG遊戲構建MUD(多用戶域)。完全用Python完成這個任務,既製作我喜歡的遊戲,又學習python。我遇到的一個問題是,由於問題的極端特殊性,我一直無法找到正確的答案。Python消歧

所以,這是我需要的,堅果殼。我沒有一個很好的代碼片斷,完全顯示了我需要的代碼,因爲我必須粘貼大約50行,才能使用5行代碼。

targetOptions = ['Joe', 'Bob', 'zombie', 'Susan', 'kobold', 'Bill'] 

在我們的遊戲一個cmd是攻擊,在這裏我們輸入「殭屍」,我們再繼續殺殭屍。但是,我只想輸入'a z'。我們在代碼中嘗試了一些不同的東西,但它們都是不穩定的,往往只是錯誤的。我們的一次嘗試返回類似['劍','護身符']作爲'獲得劍'的比賽。那麼,有沒有辦法搜索這個列表並讓它返回一個匹配的值?

我還需要返回值[0],如果有說,房間裏有2個殭屍,我輸入'a z'。感謝您提前給我們提供的所有幫助,我希望自己清楚自己在找什麼。請讓我知道是否需要更多信息。不要擔心整個攻擊事件,我只需要發送'zo'並獲得'殭屍'或類似的東西。謝謝!

+2

嘗試張貼你的一些失敗的嘗試。我們可以更容易地解決這個問題,而不是爲你做你的任務 – inspectorG4dget

回答

2

歡迎SO和Python!我建議你看看official Python documentation,花一些時間看看Python Standard Library中包含的內容。

difflib模塊包含一個函數get_close_matches(),它可以幫助您進行近似字符串比較。下面是它的樣子:

從difflib進口get_close_matches

def get_target_match(target, targets): 
    ''' 
    Approximates a match for a target from a sequence of targets, 
    if a match exists. 
    ''' 
    source, targets = targets, map(str.lower, targets) 
    target = target.lower() 

    matches = get_close_matches(target, targets, n=1, cutoff=0.25) 

    if matches: 
     match = matches[0] 
     return source[targets.index(match)] 
    else: 
     return None 

target = 'Z' 
targets = ['Joe', 'Bob', 'zombie', 'Susan', 'kobold', 'Bill'] 
match = get_target_match(target, targets) 
print "Going nom on %s" % match # IT'S A ZOMBIE!!! 
+0

http://ideone.com/dZJ8m 你提供的東西似乎沒有工作。 – jtsmith1287

+0

編輯:根據文檔示例,似乎這是針對拼寫校正問題的。我可以給上訴,並讓蘋果回來。在這種情況下Z不會與殭屍相匹配。小於3個字符的任何內容都會返回None。 'j'和'jo'不會返回'Joe'。 – jtsmith1287

+0

忘了調整截止時間,再試一次o / –

0
>>> filter(lambda x: x.startswith("z"), ['Joe', 'Bob', 'zombie', 'Susan', 'kobold', 'Bill']) 
['zombie'] 
>>> cmd = "a zom" 
>>> cmd.split() 
['a', 'zom'] 
>>> cmd.split()[1] 
'zom' 
>>> filter(lambda x: x.startswith(cmd.split()[1]), ['Joe', 'Bob', 'zombie', 'Susan', 'kobold', 'Bill']) 
['zombie'] 

這有幫助嗎?

filter過濾第一個arg接受的事物的列表(第2個參數)。 cmd是你的命令,cmd.split()[1]獲得空間後的部分。 lambda x: x.startswith(cmd.split()[1])是一個函數(lambda表達式),詢問「是否在空格之後以x開始命令?」

再測試,如果cmd是 「B」 接下來還有兩場比賽:

>>> cmd = "a B" 
>>> filter(lambda x: x.startswith(cmd.split()[1]), ['Joe', 'Bob', 'zombie', 'Susan', 'kobold', 'Bill']) 
['Bob', 'Bill']