python从文本fi将两个空格解释为一个

2024-04-25 18:09:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个程序从文本文件中翻译摩尔斯电码。从理论上讲,这应该是相当容易的,但问题是,我觉得文本文件的格式有点傻(它的学校工作,所以不能改变这一点)。我的意思是,在文件中,一个空格分隔两个字符(如-. ---),但两个空格等于一个单词的结尾(所以在翻译文本中是空格)。像这样:.--. .-.. . .- ... . .... . .-.. .--. .-.-.- 这就是我所拥有的,但它给了我没有空格的翻译文本。你知道吗

    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)。你知道吗


Tags: in文本程序messagefor电码linemsg
2条回答

在两个空格上拆分,首先得到每行中的单词列表,然后可以在一个空格上拆分单词,得到字符以供翻译人员使用

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))

你为什么不在两个空格上分开得到单词,然后在空格上得到字符?比如:

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!

当然,所有这些都假设您的translatordict有正确的映射。你知道吗

相关问题 更多 >