用python构建区分大小写的词典

用python构建区分大小写的词典,python,dictionary,Python,Dictionary,我的任务是创建一本词典,根据简单词典将列表中的单词lst翻译成瑞典语。如果字典里没有这个词,就原样返回。我们必须使用一个函数 问题是:我想确保单词“Merry”以小写形式读取,否则Python不会意识到我指的是字典中的键“Merry”,因为它区分大小写(因此I.lower())。但是,我希望返回的值是“上帝”而不是“上帝”,我似乎无法理解它 dictionary = {"merry": "god", "christmas": "

我的任务是创建一本词典,根据简单词典将列表中的单词
lst
翻译成瑞典语。如果字典里没有这个词,就原样返回。我们必须使用一个函数

问题是:我想确保单词“Merry”以小写形式读取,否则Python不会意识到我指的是字典中的键“Merry”,因为它区分大小写(因此
I.lower()
)。但是,我希望返回的值是“上帝”而不是“上帝”,我似乎无法理解它

dictionary = {"merry": "god", "christmas": "jul", "and": "och",
              "happy": "gott", "new": "nytt", "year": "ar"}


def translate(lst):
    new_list = []   #create an empty list to start with
    for i in lst: #to shuffle through every word in the list "lst"
        i = i.lower()   #to make sure we don't mess up the translation because of a upper case letter
        if i in dictionary.keys():  #look up in the keys
            new_list.append(dictionary[i])  #we want the value of the key i.
        else:
            new_list.append(i)  #return i if it does not exist in the dictionary.
            

    return new_list

# test
print(translate(['Merry', 'christmas', 'and', 'happy', 'new', 'year', 'mom']))

有很多方法可以做到这一点。一种是将单词的大写版本添加到词典中

dictionary = {"merry": "god", "christmas": "jul", "and": "och",
              "happy": "gott", "new": "nytt", "year": "ar"}
capitalized_dictionary = { key.capitalize():value.capitalize() for key, value in dictionary.items() }
dictionary.update(capitalized_dictionary)



def translate(lst):
    new_list = []   #create an empty list to start with
    for i in lst: #to shuffle through every word in the list "lst"
        # Don't need to convert to lower any more
        if i in dictionary.keys():  #look up in the keys
            new_list.append(dictionary[i])  #we want the value of the key i.
        else:
            new_list.append(i)  #return i if it does not exist in the dictionary.
            

    return new_list

# test
print(translate(['Merry', 'christmas', 'and', 'happy', 'new', 'year', 'mom']))
您可以使用检查输入字的第一个字符是否为大写,并将匹配字大写

dictionary={“merry”:“上帝”、“圣诞节”:“jul”、“和”:“och”,
“快乐”:“gott”,“new”:“nytt”,“year”:“ar”}
def翻译(lst):
新列表=[]
对于lst中的i:
如果dictionary.keys()中的i.lower():
match=字典[i.lower()]
如果i[0].isupper():#检查'i'的第一个字母是否为大写字母。
match=match.capitalize()#将匹配的翻译大写
新列表。追加(匹配)
其他:
新列表。附加(i)
返回新列表
#试验
打印(翻译(['Merry'、'christmas'、'and'、'happy'、'new'、'year'、'mom']))
>>>['God'、'jul'、'och'、'gott'、'nytt'、'ar'、'mom']

这很重要,在小写查找之前,您必须分析原始文件的大小写(小写、大写、标题等),并在输出上应用相同的大小写。然后,您可能会遇到第二个问题,Python很容易不进行本地化的大小写/大小写折叠(我认为它只是通过非线程安全的区域设置垃圾将责任传递给libc),但为了尊重语言规则(我不知道瑞典语是否有特殊的大小写规则),您可能需要这样做(并确保您有大小写折叠键)可能比小写更好。您是否尝试过这样做:`for i in lst:if i.lower()in dictionary.keys():`另一个问题可能是以后有些语言会改变词序,并且没有相同的大写规则。但是maybee这不是英语-瑞典语翻译的情况?那么你需要只大写第一个单词的第一个字母吗?或者整个文本中的任何大写字母吗?你到底想要什么?你想要文本中的第一个单词吗翻译的句子(列表)要大写,或者如果原文是大写的,您希望翻译的单词大写?或者您真的只希望特定的单词“上帝”大写?