翻译两种方式,如果不是键或值,则打印单词

时间:2015-06-09 07:36:31

标签: python

我遇到麻烦这个人已经查找了很多可能的解决方案而且似乎找不到合适的解决方案,我的麻烦就是我无法让程序打印输入中输入的单词如果单词isn使用Python 2.7的键或值

Tuc={"i":["o"],"love":["wau"],"you":["uo"],"me":["ye"],"my":["yem"],"mine":["yeme"],"are":["sia"]}

while True:
    #Translates English to Tuccin and visa versa

    translation = str(raw_input("Enter content for translation.\n").lower())

    #this is for translating full phrases, both ways.
    input_list = translation.split()


    for word in input_list:
        #English to Tuccin
            if word in Tuc and word not in v:
                print ("".join(Tuc[word]))

            #Tuccin to English
            for k, v in Tuc.iteritems():
                if word in v and word not in Tuc:
                    print k

3 个答案:

答案 0 :(得分:0)

您可以使用集合理解创建一组键和值,然后检查交集:

>>> set_list={k[0] if isinstance(k,list) else k for it in Tuc.items() for k in it}
set(['me', 'love', 'i', 'ye', 'mine', 'o', 'sia', 'yeme', 'are', 'uo', 'yem', 'wau', 'my', 'you'])


if set_list.intersection(input_list):
     #do stuff 

答案 1 :(得分:0)

您可以使用以下lambda查找翻译。如果该单词不存在,则返回空。

find_translation = lambda w: [(k, v) for k, v in Tuc.items() if w==k or w in v]

用法= find_translation(translation)

>>> find_translation('i')
[('i', ['o'])]

编辑:

修改结果以转换整个字符串。 由于您提到要转换单词列表,因此请使用相同的lambda并将其用于多个单词。

line = 'i me you rubbish'  # Only first three words will return something
# Let's change the lambda to either return something from Tuc or the same word back
find_translation = lambda w: ([v[0] for k, v in Tuc.items() if w==k or w in v] or [w])[0]

# Split the words and keep using find_transaction to either get a conversion or to return the same word
results_splits = [find_translation(part) for part in line.split()]

您将获得以下结果:

['o', 'ye', 'uo', 'rubbish']

您可以通过加入results_splits

将字符串重新组合在一起
' '.join(results_splits)

你得到了翻译

  

' o o o o oo rubbish'

答案 2 :(得分:0)

让我们以简单的方式执行此操作....为Tuccin to EnglishEnglish to Tuccin翻译创建两个dict。

In [28]: Tuc_1 = {k:Tuc[k][0] for k in Tuc} # this dict will help in translation from English to Tuccin

In [29]: Tuc_1
Out[29]: 
{'are': 'sia',
 'i': 'o',
 'love': 'wau',
 'me': 'ye',
 'mine': 'yeme',
 'my': 'yem',
 'you': 'uo'}

In [30]: Tuc_2 = {Tuc[k][0]:k for k in Tuc}  # this dict will help in translation from Tuccin to English 

In [31]: Tuc_2
Out[31]: 
{'o': 'i',
 'sia': 'are',
 'uo': 'you',
 'wau': 'love',
 'ye': 'me',
 'yem': 'my',
 'yeme': 'mine'}

示例用法:

In [53]: translation = "I love You"

In [54]: input_list = translation.split()

In [55]: print " ".join(Tuc_1.get(x.lower()) for x in input_list if x.lower() in Tuc_1)
o wau uo

In [56]: print " ".join(Tuc_2.get(x.lower()) for x in input_list if x.lower() in Tuc_2)


In [57]: translation = "O wau uo"

In [58]: input_list = translation.split()

In [59]: print " ".join(Tuc_1.get(x.lower()) for x in input_list if x.lower() in Tuc_1)


In [60]: print " ".join(Tuc_2.get(x.lower()) for x in input_list if x.lower() in Tuc_2)
i love you