将两个空间解释为文本文件



我正在尝试制作一个从文本文件转换莫尔斯代码的程序。从理论上讲,这应该很容易,但是问题在于,我发现文本文件的格式有点愚蠢(它的学校工作,因此无法改变)。我的意思是,在文件中,一个空间将两个字符分开(例如此-. ---),但是两个空间等于单词的末端(在翻译后的文本中,所以空间)。这样:.--. .-.. . .- ... . .... . .-.. .--. .-.-.-这就是我所拥有的,但是它给了我翻译的文字而没有空间。

    translator = {} #alphabet and the equivalent code, which I got from another file 
    message = []
    translated = ("")
    msg_file = open(msg.txt,"r")
    for line in msg_file:
        line = line.rstrip()
        part = line.rsplit(" ")
        message.extend(part)
    for i in message:
        if i in translator.keys():
            translated += (translator[i])
    print(translated)

我也不知道如何拦截行更改( n)。

为什么不在两个空格上拆分以获取单词,然后在空间上获取字符?类似:

translated = ""  # store for the translated text
with open("msg.txt", "r") as f:  # open your file for reading
    for line in f:  # read the file line by line
        words = line.split("  ")  # split by two spaces to get our words
        parsed = []  # storage for our parsed words
        for word in words:  # iterate over the words
            word = []  # we'll re-use this to store our translated characters
            for char in word.split(" "):  # get characters by splitting and iterate over them
                word.append(translator.get(char, " "))  # translate the character
            parsed.append("".join(word))  # join the characters and add the word to `parsed`
        translated += " ".join(parsed)  # join the parsed words and add them to `translated`
        # uncomment if you want to add new line after each line of the file:
        # translated += "n"
print(translated)  # print the translated string
# PLEASE HELP!

当然,所有这些都假定您的translator dict具有适当的映射。

首先在双空间上拆分以获取每行单词列表,然后您可以在单个空间上拆分单词,以获取字符以喂养您的翻译

translator = {} #alphabet and the equivalent code, which I got from another file 
message = []
translated = ("")
with open('msg.txt',"r") as msg_file:
    for line in msg_file:
        line = line.strip()
        words = line.split('  ')
        line = []
        for word in words:
            characters = word.split()
            word = []
            for char in characters:
                word.append(translator[char])
            line.append(''.join(word))
        message.append(' '.join(line))
print('n'.join(message))

最新更新