python - 尝试为 AI 过滤字典

标签 python python-3.x dictionary

您好,我目前正在上课,我们的任务之一是创建一个绞刑吏人工智能。这项作业有两个部分,目前我陷入了第一个任务,即给定刽子手谜题的状态和作为字典的单词列表,从字典中过滤掉该谜题的不可能答案。举个例子,如果给定的谜题是 t--t,那么我们应该过滤掉所有长度不是 4 个字母的单词。接下来,我们应该过滤掉第一个和最后一个字母不包含 t 的单词(即 tent 和 test 是可以接受的,但 type 和 help 应该被删除)。目前,由于某种原因,我的代码似乎从字典中删除了所有条目,我不知道为什么。非常感谢您的帮助。我还在下面附上了我的代码以供引用。

def 过滤器(自身,拼图):

wordlist = dictionary.getWords()

newword = {i : wordlist[i] for i in range(len(wordlist)) if len(wordlist[i])==len(str(puzzle))}

string = puzzle.getState()

array = []
for i in range(len(newword)):
    n = newword[i]
    for j in range(len(string)):
        if string[j].isalpha() and n[j]==string[j]:
            continue
        elif not string[j].isalpha():
            continue
        else:
            array+=i
            print(i)
            break
array = list(reversed(array))
for i in array:
    del newword[i]

一些附加信息:

puzzle.getState() 是一个提供给我们的函数,它返回一个描述拼图状态的字符串,例如。 a-a--- 或 t---t- 或 elepha--

dictionary.getWords 本质上是根据单词列表创建字典

谢谢!

最佳答案

这可能有点晚了,但是使用正则表达式:

import re

def remove(regularexpression, somewords):
    words_to_remove=[]
    for word in somewords:
       #if not re.search(regularexpression, word):
        if re.search(regularexpression, word)==None:
            words_to_remove.append(word)
    for word in words_to_remove:
            somewords.remove(word)

例如,您有列表 words=['hello', 'halls', 'harp', 'heroic', 'tests']

您现在可以执行以下操作: remove('h[a-zA-Z]{4}$', Words)words 将变为 ['hello', 'halls'],而 remove('h[a-zA-Z]{3}s$', Words) 仅将 words 保留为 ['halls' ]

关于python - 尝试为 AI 过滤字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42869875/

相关文章:

python - 将三级定界的字符串解析成字典

python - Spark SQL Row_number() PartitionBy Sort Desc

python - 打印特定字符的所有字符串索引位置

python - 如何在 mechanize for python 中选中复选框并运行与该复选框关联的事件?

python - 为什么我在使用 Twitter Rest API 时收到此错误

python-3.x - struct.error : unpack requires a buffer of 4 bytes

c# - 谁能解释为什么 C# 中的 Dictionary<> 不像 STL 中的 map<T,U> 那样工作?

python - 将现有大写字母保留在字符串中

python - 如何解码 python 中的反斜杠转义字符串?

javascript - 如何排列映射而不是嵌套的 for 循环