简体   繁体   English

需要帮助在 python 中制作一个简单的字典

[英]Need help to make a simple dictionary in python

I need a simple dictionary which works like this: first it takes the number of words(n) which we have the translations in 4 languages, then we enter on each line (totally n line) the words we have with their translations seperarated by space as dictionary source, then we need to ask user to enter a phrase which might have more than words it was provided before as dictionary source, and the phrase can be in not only one specific language, for example it might be a mix of English, French and German, but we need to translate the phrase to the first language which is Persian in our case, and if there's no translation it will simply print the word itself.我需要一个简单的字典,它的工作原理是这样的:首先它需要我们有 4 种语言翻译的单词数(n),然后我们在每行(总共 n 行)输入我们有的单词,并用空格分隔它们的翻译作为字典源,那么我们需要要求用户输入一个短语,该短语可能比之前作为字典源提供的单词多,并且该短语不仅可以是一种特定语言,例如它可能是英语的混合,法语和德语,但我们需要将短语翻译成第一种语言,在我们的例子中是波斯语,如果没有翻译,它只会打印单词本身。 so here is the code :所以这里是代码:

def read_dictionary():
for i in range(0, words_num):
    dict_words = str(input())
    words[dict_words.split()[0]] = dict_words.split()[1:]


def translator():
    translation = ""
    input_phrase = str(input("Enter your phrase to translate please: ")).split()
    for word in input_phrase:
        for k, v in words.items():
            if word in v:
                translation += (k + " ")
            else:
                translation += (word + " ")
    print(translation)

words_num = int(input("Enter the number of existing translated words in dictionary: "))
words = {}
read_dictionary()
translator()

so here's sample input and desired output:所以这里是示例输入和所需的输出:

**input:**
Enter the number of existing translated words in dictionary: 
4
man I je ich        
kheili very très sehr
alaghemand interested intéressé interessiert 
barnamenevisi programming laprogrammation Programmierung
Enter your phrase to translate please: 
I am very interested in programming
**output:**
man am kheili alaghemand in barnamenevisi

but it output like this instead:但它的输出是这样的:

man I I I am am am am very kheili very very interested interested alaghemand interested in in in in programming programming programming barnamenevisi 

The issue stems from your translator() function.问题源于您的translator()函数。

For each word in the input_phrase , you iterate through each k, v pair in words.items() .对于input_phrase中的每个word ,您遍历words.items()每个k, v对。 Good so far.目前很好。

So what do we want to happen?那么我们想要发生什么? We want to look through each pair of k, v until we find a matching word (in v ), then (if we do) we want to add the key k to the translation we're building.我们想要查看每对k, v直到找到匹配的单词(在v ),然后(如果我们这样做)我们想要将键k添加到我们正在构建的translation If we don't find a matching word, we just add the original word value to translation .如果我们没有找到匹配的单词,我们只需将原始word值添加到translation

The problem with your code is that even if you do find a word, you keep looking through the remaining keys in the dictionary.您的代码的问题在于,即使您确实找到了一个单词,您也会继续查看字典中剩余的键。 Also, for each key in the dictionary you're either adding it's translation, or the starting word , when you should only be adding the base word if you don't find a match.此外,对于字典中的每个键,您要么添加它的翻译,要么添加起始word ,如果找不到匹配项,则只应添加基本word

Personally, I would move your inner for loop into a new function called translate_word() or something similar, but a simple way to fix your translator() function without major changes is as follows:就个人而言,我会将您的内部for循环移动到一个名为translate_word()或类似的新函数中,但无需重大更改即可修复您的translator()函数的简单方法如下:

def translator():
    translation = ""
    input_phrase = str(input("Enter your phrase to translate please: ")).split()
    for word in input_phrase:
        found = False
        for k, v in words.items():
            if word in v:
                translation += (k + " ")
                found = True
                break
        if not found:
            translation += (word + " ")
    print(translation)

In the new translator() function, you can see that for each new word, you set a variable found to False .在新的translator()函数中,您可以看到,对于每个新单词,您都将found变量设置为False found will represent whether or not you have found a suitable translation in the dictionary. found将代表您是否在字典中找到了合适的翻译。

You'll then iterate through the dictionary.然后您将遍历字典。 If you find a match, you add k to the translation, set found to True (because you've found a translation), and break out of the inner for loop.如果找到匹配项,则将k添加到翻译中,将found设置为True (因为您找到了翻译),然后break内部for循环。

Once out of the inner for loop, you check if you had found a translation for word .一旦离开内部for循环,您检查是否foundword的翻译。 If you did not find a translation, you simply add the word to the translation .如果您没有找到翻译,您只需将word添加到translation

Instead of one dictionary(containing three languages) for each word, you can define a dictionary for each language something like :您可以为每种语言定义一个字典,而不是为每个单词定义一个字典(包含三种语言),例如:

dct_eng=dict(), dct_frnch=dict() , dct_grmn=dict()

key of each dictionary is the first word from input, this key is same for all three and respectively value of each dict will be second and third and forth word rom input now you can loop through each word and again loop through each value in dictionary to find corresponding keys of value and finally use found = False mechanism like Kieran Moynihan mentioned to get translation of word or get word itself in case translation does not exist in dictionaries.每个字典的键是输入的第一个单词,这三个键都相同,每个字典的值分别是第二个和第三个和第四个单词 rom 输入现在您可以遍历每个单词并再次遍历字典中的每个值找到相应的值键,最后使用 found = False 机制,如 Kieran Moynihan 提到的获取单词的翻译或获取单词本身,以防字典中不存在翻译。

translation=''
for word in sentence:# sentence is a list of words which user inputs
found=False
for item in words_dct_eng.keys():
    if word== words_dct_eng[item]:
        translate+=str(item)+' '
        found = True
    if word == words_dct_frch[item]:
        translate += str(item) + ' '
        found = True
    if word == words_dct_grmn[item]:
        translate += str(item) + ' '
        found=True
if not found:
    translate += str(word) + ' '

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM