[英]Sorting a through a list of words in python
我正在編寫一個程序,其中用戶猜測一個秘密單詞中的字母(游戲劊子手)用戶猜到一個正確的字母后,它會生成一個格式為“t _ _ t”的字符串。 我正在嘗試編寫一個程序,將這個猜測與單詞 kist 進行比較並打印出可能答案的單詞(相似的長度並包含同一索引中的猜測字母)
到目前為止,這是我的代碼
...
def match_with_gaps(my_word, other_word):
my_word_edited = my_word.split()
the_len_my_word = len(my_word_edited)
words_with_same_length = []
i = " "
for word in other_word:
the_len_other_word = len(word)
if the_len_other_word == the_len_my_word:
for i in range(the_len_my_word):
letter_in_my_word = my_word_edited[i]
letter_in_other_word = word[i]
# if letter_in_my_word != "_"
if letter_in_my_word == letter_in_other_word:
words_with_same_length.append(word)
print(words_with_same_length)
...
最有效的方法是對包含在單個(多行)字符串中的單詞列表使用正則表達式,每個單詞一行。
with open("/usr/share/dict/words","r") as wordList:
allWords = wordList.read().lower()
import re
def matchGaps(my_word):
seenLetters = "".join(set(my_word.lower()))
pattern = "^"+my_word.lower().replace("_",f"[^{seenLetters}]")+"$"
return re.findall(pattern,allWords,re.MULTILINE)
output:
print(matchGaps("tre_")) # will not propose "tree"
['tref', 'trek', 'trey']
print(matchGaps("tr__")) # will not propose "trot"
['trag', 'trah', 'tram', 'tran', 'trap', 'tray', 'tree', 'tref', 'trek', 'trey', 'trey', 'trig', 'trim', 'trin', 'trio', 'trio', 'trip', 'trix', 'trod', 'trog', 'tron', 'trow', 'troy', 'troy', 'trub', 'true', 'trug', 'trun', 'tryp']
print(matchGaps("_ree"))
['bree', 'cree', 'dree', 'free', 'gree', 'tree']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.