我正在尝试制作一个从文本文件中翻译莫尔斯电码的程序。理论上它应该很容易但问题是我发现文本文件的格式有点傻(它的学校工作所以不能改变它)。我的意思是,在文件中,一个空格分隔两个字符(如此-. ---
),但两个空格等于一个单词的结尾(因此翻译文本中的空格)。像这样:.--. .-.. . .- ... . .... . .-.. .--. .-.-.-
这就是我所拥有的,但它为我提供了没有空格的翻译文本。
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)。
答案 0 :(得分:0)
为什么不分开两个空格来获取单词,然后在空格中获取字符?类似的东西:
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有正确的映射。
答案 1 :(得分:0)
首先在双倍空格中拆分以获取每行中的单词列表,然后您可以在单个空格中拆分单词以获取字符以便为翻译人员提供
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))