[英]using python regex on tuples to filter user inputs
我想使用正則表達式基於一組元組過濾用戶輸入。 如果在set of tuples
找不到用戶輸入並且該輸入不是an alphanumeric character
則應返回錯誤消息。 我不知道如何在python regex代碼中訪問元組。 所以我傳入了src.items()
,如何使用轉義功能獲取src.items()
來引入其值,或者也許我不應該這樣做。
我的代碼:
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)
首先,這里有一個冗余:
如果在元組集中找不到用戶輸入並且該輸入不是字母數字字符,則應該返回錯誤消息
如果用戶輸入位於您的元組集中,那么它如何包含非字母數字字符? 另外,您不指定是一次測試單個單詞還是完整短語。
讓我們嘗試另一種方法。 首先,不要使用兩個級別的數據結構(即只是字典)。其次,我們將元組切換為列表,不是出於技術原因,而是出於語義原因(同質->列表,異質->元組)。 現在,我們將使用正則表達式,以簡單的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
從這里開始,您可能會考慮允許一些動詞,例如逗號和句點,並簡單地剝離它們而不是對其進行判斷。
這不是使用正則表達式的好地方,這與有效的Python正則表達式完全不同。
最好只是在循環中檢查用戶輸入(可能被強制為小寫)是否等於任何命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.