words.json是网上找的 差不多13000个
值得注意的是wordle对多个相同字符的判定很奇怪
import json
with open("words.json", 'r') as f:
data = json.load(f)
words = data['words']
# 初始化
fault = "" # 灰色色块
pos_wrong = ["", "", "", "", ""] # 黄色色块
right = ["", "", "", "", ""] # 绿色色块
# 提示
print(40 * "-")
print("gray:0 yellow:1 green:2")
print("If there are same characters in the word and one (or more) of them is grey, put it (them) 1")
print(40 * "-")
def calculate_word_weights(word_list):
word_weights = {}
for word in word_list:
weight = sum([word.count(char) for char in set(word)]) # 计算权重
word_weights[word] = weight
return word_weights
def generate_word_suggestions(word_list, fault, pos_wrong, right):
suggestions = []
for word in word_list:
flag = True
for try_from_vocab in fault:
if try_from_vocab in word:
flag = False
break
if not flag:
continue
for n in range(5):
if right[n] != "" and right[n] != word[n]:
flag = False
break
if pos_wrong[n] != "":
for ps in pos_wrong[n]:
if ps not in word:
flag = False
break
else:
if word.index(ps) == n:
flag = False
break
if flag:
suggestions.append(word)
return suggestions
word_weights = calculate_word_weights(words)
sorted_words = sorted(words, key=lambda x: word_weights[x], reverse=True)
for i in range(5):
guess = input("{0}: ".format(i + 1))
results = input("result: ")
for n in range(len(results)):
if results[n] == "0":
fault += guess[n]
elif results[n] == "1":
pos_wrong[n] += guess[n]
elif results[n] == "2":
right[n] = guess[n]
suggestions = generate_word_suggestions(sorted_words, fault, pos_wrong, right)
print("Suggested words:", suggestions)
print(40 * "-")
sorted_words = suggestions.copy()