python - 检查python dict中的值

标签 python

我正在尝试从用户输入中获取关键字,如果词典中有单词(dict),则返回一个元组(token, word),否则返回('error', word)

我将词典数据存储在字典中,每个键都有多个值,并循环查看输入的单词是否在其中一个中。

lexicons = {
    'direction': ['north', 'south', 'east', 'west'],
    'noun': ['car', 'bike'],
}

def scan(sentence):

    result = []
    words = sentence.split()

    for key, value in lexicons.items():  
        for word in words:
            found = 0
            if word in value:
                found += 1
            else:
                pass

            if found == 1:
                result.append((key, word))
            else:
                result.append(('error', word))

    return result

scan('car bike QWER')

我希望的是:

[('名词', '汽车'),('名词', '自行车'),('错误', 'QWER')]

但是我得到了:

[('错误', '汽车'),('错误', '自行车'),('错误', 'QWER'),('名词', '汽车'),('名词', '自行车'),('错误', 'QWER')]

我知道那是因为它会检查字典中的每个键,但我不知道如何修改它。

谢谢!

最佳答案

像这样:

lexicons = {
    'direction': ['north', 'south', 'east', 'west'],
    'noun': ['car', 'bike'],
}

def scan(sentence):

    result = []
    words = sentence.split()

    for word in words:
        found = False
        for key, value in lexicons.items():              
            if word in value:
                found = True
                result.append((key, word))
                break
        if not found:
            result.append(('error', word))
    return result

scan('car bike QWER')

关于python - 检查python dict中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745327/

相关文章:

python - 在 python 中指定日期时间所在的时区

python - 生成指定长度的嵌套列表

python浮点到字符串没有精度损失

python - 解决 conda 中的包分辨率

python - 根据列值创建列表,并使用该列表从 df 中的字符串列中提取单词,而不用 for 循环覆盖行值

python - DataFrame基于多列应用函数,也为多列设置值

项目的 python 设置 - 循环导入/依赖注入(inject)

python - 将 numpy.stack() 与 numba njit 一起使用时出现 TypingError

python - 使用 lxml 一次对一个 .xml 项(及其子项)执行函数操作

python - 启动带有输出和超时的 python 进程