简体   繁体   English

如何读入文本文件、创建字典、读入另一个文本文件并用所述字典翻译并将其写入新文件

[英]How to read in a text file, create a dictionary, read in another text file and translate it with said dictionary and write it into a new file

hey guys so I'm working on a (for me) complicated code and I'm kinda stuck.嘿伙计们,我正在处理(对我而言)复杂的代码,但我有点卡住了。 The task is that I should write a programm which reads in a dictionary (file.txt is given), and translate another text with this dictionary (also given so it must be read in too) and then save the translated text into a new file (which I gotta create).任务是我应该编写一个读取字典的程序(给出了 file.txt),然后用这个字典翻译另一个文本(也给出了所以它也必须读入),然后将翻译的文本保存到一个新文件中(我必须创建)。

I think I got it so far that the dictionary is read in but then I'm pretty much lost.我想到目前为止我已经读过字典了,但后来我几乎迷路了。 I was trying to do an if loop conditional (if the key is in the text I gotta translate, it should be replaced by the value) but I can't go on from there.我试图做一个 if 循环条件(如果键在我要翻译的文本中,它应该被值替换)但我不能从那里继续。

So here's what I got so far:所以这是我到目前为止所得到的:

dictionary = {}

with open("dict.txt") as dict:
    for line in dict:
        wordPair = line.split()
        dictionary[wordPair[0]] = wordPair[1]

def get_translations(dict):
    dict = get_translations("dict.txt")
    return get_translations(dict)

def translate(dict, text1, trnsl):
    with open("text1.txt") as text1, open("trnsl.txt", "w") as trnsl:
        for wordPair in dict:
            if wordPair == True: #that's where I can't figure it out.

Sidenote: if any word can't be translated from the given dictionary (because it's not part of the dictionary), it should be indicated by these "<>".旁注:如果有任何单词不能从给定的词典中翻译出来(因为它不是词典的一部分),则应该用这些“<>”表示。 I guess a simple else: print word + "<>" would do?我想一个简单的其他:打印单词+“<>”可以吗?

Thanks for ANY suggestions!感谢您的任何建议!

You have to specify if there's punctuation or stuff.您必须指定是否有标点符号或其他内容。

I'm going to assume just spaces and words.我将只假设空格和单词。

def translate(dict, text1, trnsl):
    with open("text1.txt") as text1, open("trnsl.txt", "w") as trnsl:
        for line in text1: # parse each line
            words = line.split() # break line into words, do more stuff here if punctuation
            for word in words:
                if word in dict: # check if translatable
                    trnsl.write(dict[word]) # get translation
                else:
                    trnsl.write(word)
                trnsl.write(' ') # re-add spaces between words
            trnsl.write('\n') # re-add endlines between lines

If I understand your question correctly, you want to be looping through the dictionary like this in order to obtain the key and the value of each item:如果我正确理解你的问题,你想像这样循环字典以获得每个项目的键和值:

for key, value in dictionary.items():
    # Do something with the key or the value here.

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

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