用字典翻译短语?(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

将这两个值作为键存储在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

您已接近目标:

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"]

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

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

如果键存在,这将返回键的值,如果不存在,则返回第二个参数中所述的值(此处为空字符串)。字典的键可以是你想要的任何不可变对象。

只要可能,您可以使用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()来处理诸如单词后面跟着标点符号之类的情况。

最新更新