搜索程序中具有相同值的不敏感键

2024-09-30 22:10:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查一个文本包含一个词的某处和同一个词的第一个字母大写在一个句子的开头。然后,我希望能够在字典中使用搜索程序中的一个命令来标记两者。你知道吗

例如,有一个包含“the”和“the”的文本,我想编一本字典,既能识别“determinator”,又不必把每个单词都定义为“determinator”:

dict['the']='DETERMINER'
dict['The]='DETERMINER'

等等


Tags: the标记文本命令程序字典定义字母
3条回答

既然您似乎是一个初学者,我将向您推荐一个更详细的代码:

dic = {'tiger':'animal','Tiger':'animal','rose':'plant'}
result = {}
for key in dic:
    dic[key.lower()] = dic[key] # the key is always in lower case. If it exists already, it will be overriden.
print(result)

这应该可以帮助你开始。您可以检查同一个小写键的不同值并抛出错误。你知道吗

有两个选项,其中您有重复的关键点。你知道吗

按插入顺序取最后一个值

在python3.7+(或者作为实现细节的cpython3.6)中,您可以通过插入顺序获取最后一个值。在其他情况下,不应假定秩序。你知道吗

dic = {'tiger': 'animal', 'Tiger': 'animal2', 'rose': 'plant'}  # example input
newdic = {k.casefold(): v for k, v in dic.items()}

{'rose': 'plant', 'tiger': 'animal2'}

首选小写或大写值

小写字母:

newdic = {k.casefold(): dic.get(k.casefold(), v) for k, v in dic.items()}

{'rose': 'plant', 'tiger': 'animal'}

同样,对于大写:

newdic = {k.capitalize(): dic.get(k.capitalize(), v) for k, v in dic.items()}

{'Rose': 'plant', 'Tiger': 'animal2'}

你可以做:

dic = {'tiger':'animal','Tiger':'animal','rose':'plant'}
result = { key.lower() : value for key, value in dic.items() }
print(result)

输出

{'tiger': 'animal', 'rose': 'plant'}

相关问题 更多 >