使用字典翻译短语? (蟒蛇)

时间:2014-11-06 23:58:04

标签: python

我必须使用我的字典将短语粗略翻译成英文,但我不确定如何。

c1 = "befreit"
c2 = "baeche"
c3 = "eise"
c4 = "sind"
c5 = "strom"
c6 = "und"
c7 = "vom"

mydict = {c1:"liberated", c2:"brooks", c3:"ice", c4:"are", c5:"river", c6:"and", c7:"from"}

print(mydict.keys())
print(mydict.values())

phrase = "vom eise befreit sind strom und baeche"
print(phrase)

phrase.split()
for x in phrase:
    #something goes here

3 个答案:

答案 0 :(得分:1)

将dict作为键存储在你的dict中:

 mydict = {"befreit":"liberated", "baeche":"brooks", "eise":"ice", "sind":"are", "strom":"river", "und":"and", "vom":"from"}


phrase = "vom eise befreit sind strom und baeche"
print(" ".join([mydict[w] for w in phrase.split()]))
from ice liberated are river and brooks

答案 1 :(得分:0)

您可以使用dict将原始短语中的每个单词尽可能地映射到所需的语言:

c1 = "befreit"
c2 = "baeche"
c3 = "eise"
c4 = "sind"
c5 = "strom"
c6 = "und"
c7 = "vom"

mydict = {c1:"liberated", c2:"brooks", c3:"ice", c4:"are", c5:"river", c6:"and", c7:"from"}

phrase = "vom eise befreit sind strom und baeche"
translated = " ".join([mydict.get(p, p) for p in phrase.split(' ')])
print translated
# from ice liberated are river and brooks

请注意,您可能需要使用更谨慎的标记化方案,而不是使用split(),以处理单词后跟标点符号等情况。

答案 2 :(得分:0)

你快到了:

c1 = "befreit"
c2 = "baeche"
c3 = "eise"
c4 = "sind"
c5 = "strom"
c6 = "und"
c7 = "vom"

mydict = {c1:"liberated", c2:"brooks", c3:"ice", c4:"are", c5:"river", c6:"and", c7:"from"}

print(mydict.keys())
print(mydict.values())

phrase = "vom eise befreit sind strom und baeche"
print(phrase)

translated_string = " ".join([mydict.get(e, "") for e in phrase.split(" ")])
print translated_string

查看语法的词典与列表非常相似: 输入

element = mylist[0]

你问清单“给我索引0处的元素”。 对于词典,你可以做类似的事情:

value = mydict["key"]

但是,如果密钥不在字典中,您将收到一个keyerror,您的程序将崩溃。另一种方法是使用get():

value = mydict.get("key","")

这将返回键的值(如果它存在),如果不存在,则返回您在第二个参数中声明的任何内容(此处为空字符串)。字典的键可以是您想要的任何不可变对象。在你的情况下是一个字符串。