【问题标题】:Translating to english using word lists使用单词列表翻译成英语
【发布时间】:2019-10-12 16:52:37
【问题描述】:

假设我有一个项目颜色对的列表:

Item1 红色

Item2 red_in_finnish

Item3 red_in_polish

Item4 blue_in_russian

Item5 blue_in_estonian

Item6 blue_in_polish

我需要把所有外语的颜色翻译成英文:

Item1 红色

Item2 红色

Item3 红色

Item4 蓝色

Item5 蓝色

Item6 蓝色

在我的实际代码中,我有两种以上的颜色,以及大约十几个不同的数组,其中包含每种颜色的所有外来词。这是我当前执行替换的方式:

red_words = ['red_in_finnish', 'red_in_polish']
blue_words = ['blue_in_russian', 'blue_in_estonian', 'blue_in_polish']

for word in red_words:
   if word in item_name:
      item_name = item_name.replace(word, "red")

问题是我事先不知道每个名称是否包含任何特定颜色,因此我需要检查所有名称以确保替换所有内容。

有没有聪明的方法来做到这一点?如果能够以某种方式将颜色的外文名称映射到它们的英文名称,那将是完美的。

【问题讨论】:

    标签: python replace


    【解决方案1】:

    你也可以尝试使用字典

    item_name = "hello my color is red_in_estonian"
    dic = {
        "red_in_estonian"  :  "red",
        "red_in_german"    :  "red",
        "blue_in_estonian" :  "blue",
        "blue_in_german"   :  "blue",
    }
    for word in item_name.split(" "):
        try:
            translation = dic[word]
            item_name = item_name.replace(word, translation)
    
        except:
            pass
    

    【讨论】:

      【解决方案2】:

      如果我理解正确,您可以通过使用 dict 迭代一次 list 来做到这一点。一个例子:

      red_words = {'red': 'red', # English
                   'rojo': 'red', # Spanish
                   'rot': 'red', # German
                   'rouge': 'red' # French
                  }
      
      blue_words = {'blue': 'blue',
                    'azul': 'blue',
                    'blau': 'blue',
                    'bleu': 'blue'
                   }
      
      # More colours here...
      
      combined_translations = {**red_words, **blue_words}
      
      data = [('blue_thing', 'bleu'), 
              ('also_blue_thing', 'azul'), 
              ('blueberry', 'blue'),
              ('fire engine', 'red'),
              ('blood', 'rouge'),
              ('tomato', 'rot')]
      
      translated = [(item, combined_translations[colour]) for item, colour in data]
      
      print(translated)
      

      输出:

      [('blue_thing', 'blue'), 
       ('also_blue_thing', 'blue'), 
       ('blueberry', 'blue'), 
       ('fire engine', 'red'), 
       ('blood', 'red'), 
       ('tomato', 'red')]
      

      如果出于某种不正当的机会,您有一个单词在两种源语言中是相同的,但在英语中每个表示不同的颜色,这将失败。

      【讨论】:

        【解决方案3】:

        你可以使用Goslate (Free Google Translate API)

        import goslate
        gs = goslate.Goslate()
        
        for word in words:
            print(gs.translate(word, 'en'))
        

        【讨论】:

        • 这是一个很好的解决方案,但是如果某些颜色在波兰语中类似于“钢灰色”,而我需要它们在英语中只是“灰色”,那么翻译无法做到这一点...
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多