在Python中如何用字典值更改字符串的值

2024-10-01 22:39:11 发布

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

我有以下Python词典:

myDict = {"how":"como", "you?":"tu?", "goodbye":"adios", "where":"donde"}

使用类似于:"How are you?"的字符串,我希望将以下结果与myDict进行比较:

"como are tu?"

正如您所看到的,如果一个单词没有像“are”那样出现在myDict中,那么结果会显示为它。你知道吗

这是我的代码直到现在:

myDict = {"how":"como", "you?":"tu?", "goodbye":"adios", "where":"donde"}

def translate(word):
    word = word.lower()
    word = word.split()

    for letter in word:
        if letter in myDict:
           return myDict[letter]

print(translate("How are you?"))

结果只得到了第一个字母:como,那么我没有得到整个句子又做错了什么呢?你知道吗

感谢您的帮助!你知道吗


Tags: inyouwherearemydicttranslatehowword
3条回答

当您调用return时,当前正在执行的方法被终止,这就是您的方法在找到一个单词后停止的原因。要使方法正常工作,必须附加到String中,该String作为局部变量存储在方法中。你知道吗

下面是一个函数,它使用列表理解来翻译String,如果它存在于dictionary

def translate(myDict, string):
    return ' '.join([myDict[x.lower()] if x.lower() in myDict.keys() else x for x in string.split()])

示例:

myDict = {"how": "como", "you?": "tu?", "goodbye": "adios", "where": "donde"}

print(translate(myDict, 'How are you?'))

>> como are tu?

函数在第一次碰到return语句时返回(退出)。在这种情况下,这永远是第一个词。你知道吗

你应该做的是列一个单词列表,如果你看到当前的返回,你应该添加到列表中。你知道吗

添加每个单词后,可以在末尾返回列表。你知道吗

附言:你的术语很混乱。你有的是短语,每个短语都是由单词组成的。”这是一个短语“是一个短语,由4个单词组成:“This”,“is”,“a”,“短语”。字母应该是单词的单独部分,例如“This”中的“T”。你知道吗

问题是,您将返回映射到词典中的第一个单词,因此您可以使用它(我更改了一些变量名,因为这有点混乱):

myDict = {"how":"como", "you?":"tu?", "goodbye":"adios", "where":"donde"}

def translate(string):
    string = string.lower()
    words = string.split()
    translation = ''

    for word in words:
        if word in myDict:
           translation += myDict[word]
        else:
           translation += word
        translation += ' ' # add a space between words

    return translation[:-1] #remove last space

print(translate("How are you?"))

输出:

'como are tu?'

相关问题 更多 >

    热门问题