有没有一种方法可以获取将字符串转换为与输入顺序相同的函数的输出?

时间:2019-04-24 17:44:12

标签: python list dictionary

很抱歉,标题令人困惑。我正在研究的练习是编写一个带有两个参数的函数:将瑞典语单词映射到英语的字典,以及与瑞典语句子相对应的字符串。该功能应将句子翻译成英语

我的函数在翻译方面效果很好,但是它产生的输出顺序错误。

例如,以下参数由字典和瑞典语字符串组成(例如:“好猴子”)

translate_sentence({'en': 'a', 'fin': 'fine', 'apa': 'monkey'}, 'en fin apa')  

应该返回

'a fine monkey'

但它返回

'a monkey fine'

以下是该函数的脚本:


def translate_sentence(d, sentence): 
    result = []                     
    delimiter = ' '                 
    s = sentence.split()            
    for word in d:                        
        if word in sentence and word in d:
            d_word = (d[word])
            result.append(d_word)
    for word in s:                          
        if word in s and word not in d:
            s_word = word
            result.append(s_word)
    return delimiter.join(result)    

正如我之前说的,问题在于该函数返回的翻译字符串带有错误顺序的单词。我知道python字典没有顺序,难道没有某种方法可以使输出与句子顺序相同吗?

2 个答案:

答案 0 :(得分:1)

这种单线似乎工作正常。在字典中查找每个单词,并按与输入句子相同的顺序加入。

def translate_sentence(d, sentence): 
    return ' '.join(d.get(word, word) for word in sentence.split())

示例:

>>> translate_sentence({'en': 'a', 'fin': 'fine', 'apa': 'monkey'}, 'en fin apa')  
'a fine monkey'
>>> 

答案 1 :(得分:1)

我们检查每个键的值,其中key是字符串中的一个单词,如果找不到,我们将使用原始单词

def translate_sent(d, s): 
    return ' '.join(d[word] if word in d else word for word in s.split())

>>> translate_sent({'en': 'a', 'fin': 'fine', 'apa': 'monkey'},        'en fin apa')  
'a fine monkey'
>>> translate_sent({'en': 'a', 'fin': 'fine'}, 'en fin apa')  
‘a fine apa’