2017-12-10 3 views
-2

私はモールス符号をテキストファイルから変換するプログラムを作ろうとしています。理論的には非常に簡単なはずですが、問題はテキストファイルの書式がちょっとばかげていることです(その学校の仕事はそれを変更できません)。私はそれが意味することは、ファイル内で1つのスペースが2つの文字(このような-. ---のような)を区切りますが、2つのスペースは単語の末尾と同じです(翻訳されたテキストのスペースなので)。このように:.--. .-.. . .- ... . .... . .-.. .--. .-.-.- これは私が持っているものですが、それは私にスペースがない翻訳されたテキストを与えます。python - テキストファイルから2つの空白を1つに解釈する

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)をインターセプトする方法も知らない。

+2

を養うために、文字を取得するために、単一のスペースで単語を分割することができますあなたはどこで最初のパスを行うことができます単語を分けてリストに入れてください。 "2つのスペース"を解釈してから、2番目のパスでこの個々の単語のリストを処理します(今回は、 "1つのスペース"について心配する必要があります)。翻訳された単語を1つずつリストに戻し、そのリストを(スペースで区切って)印刷します。あなたはすでにPythonで必要なすべてのツール、幸運を知っているようです。 – bgse

+0

例を練習するために、[チュートリアル](https://docs.python.org/3/tutorial/index.html)を通して少し時間を費やす必要があります。 Pythonが提供するツールについて紹介し、問題解決のためのアイデアを得ることさえできます。 – wwii

+0

split on * double-space *最初に各行の単語のリストを取得すると、単語を1つのスペースに分割して文字を取得して翻訳者に送ることができます。 – wwii

答えて

0

あなたは2つのスペースで分割して単語を取得し、その後スペースに文字を取得するのはなぜですか?ような何か:もちろん

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辞書を想定し、適切なマッピングを持っています。

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)) 
関連する問題