2016-06-25 35 views
0

我想使用正則表達式來基於一組元組來過濾用戶輸入。如果在set of tuples中找不到用戶輸入,並且不是an alphanumeric character,則應該返回錯誤消息。我不知道如何訪問我的python正則表達式代碼中的元組。所以我通過了src.items(),我該如何使用逃生功能讓src.items()帶來它的價值,或者我不應該這樣做。在元組上使用python正則表達式來過濾用戶輸入

我的代碼:

import re 

direction = ('north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back') 
verb = ('go', 'stop', 'kill', 'eat') 
stop = ('the', 'in', 'of', 'from', 'at', 'it') 
noun = ('door', 'bear', 'princess', 'cabinet')  

src = {'direction': direction, 
     'verb': verb, 
     'stop': stop, 
     'noun': noun 
     } 

# use this to pick out error strings from user input 
    er = r"*[\W | src.items()]" 
    ep = re.compile(er, re.IGNORECASE) 

回答

0

這是不使用正則表達式的好地方,那就是完全不像一個有效的Python正則表達式。

您最好只是檢查用戶輸入(可能是強制小寫)是否等於任何命令,在循環中。

1

首先,有一個冗餘的位置:

如果用戶輸入不 中發現的元組的應返回的錯誤信息,而不是字母數字字符

如果用戶輸入在你的元組集合中,它如何包含非字母數字字符?此外,您也沒有指定是否一次測試單個單詞或完成短語。

讓我們嘗試一種不同的方法。首先,不要使用兩層數據結構(即只是字典)。其次,我們將元組切換到列表,不是出於技術原因,而是出於語義原因(均勻 - >列表,異構 - >元組)。我們現在拋出正則表達式來支持簡單的split()in測試。最後,我們來測試完整的短語:

vocabulary = { 
    'direction': ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'], 
    'verb': ['go', 'stop', 'kill', 'eat'], 
    'stop': ['the', 'in', 'of', 'from', 'at', 'it'], 
    'noun': ['door', 'bear', 'princess', 'cabinet'] 
    } 

vocabulary_list = [word for sublist in vocabulary.values() for word in sublist] 

phrases = ["Go in the east door", "Stop at the cabinet", "Eat the bear", "Do my taxes"] 

# use this to pick out error strings from user input 
for phrase in phrases: 
    if any(term.lower() not in vocabulary_list for term in phrase.split()): 
     print phrase, "-> invalid" 
    else: 
     print phrase, "-> valid" 

產生

Go in the east door -> valid 
Stop at the cabinet -> valid 
Eat the bear -> valid 
Do my taxes -> invalid 

從這裏,你可能會考慮允許一些puctuation像逗號和句號,只是帶他們,而不是審判他們。

+0

我一次測試完整的短語。 –

相關問題