2017-10-30 5 views
0

私は.txtファイルに追加した文にピリオドを追加するループを利用しようとしています。
しかし、私はループを実行するたびに、私の結果は毎回の期間を追加するコードで終了することがわかります。ループエラーを置換する

sentences = input_file.read() 
    matches = re.finditer("('The dog is happy",sentences,re.MULTILINE) 
    if matches: 
    for match in matches: 
     temp_match = match[1] 
     sentences = sentences.replace(temp_match, temp_match + '.') 
    output_file.write(sentences) 

    input_file.close() 
    output_file.close() 

私は取得していますエラーの例はこれです:

The dog is happy. 
The dog is happy.. 
The dog is happy... 

私はこのループを止めるために何ができますか?

+1

'file_contents.replace("犬は幸せです "、"犬は幸せです ")' – jordanm

+2

'file_contents_v2 = file_contents'はファイルの内容を別々にコピーしません。どちらの名前も_same_値を参照します。 –

+1

なぜ文字列の末尾にピリオドを追加する正規表現が必要ですか? –

答えて

0

あなたの正規表現はあなたが既にピリオドを追加したことを気にしていません。これは、任意の期間の前にテキストを見つけて、同じものにピリオドを置き換えるため、各繰り返しでピリオドが累積されます。

ファイルの行を読み、そうでない場合は、追加しますか?

with open("in.txt") as input_file, open("out.txt") as output_file: 
    for line in input_file: 
     if not line.rstrip().endswith("."): 
      output_file.write(line.rstrip() + r".\n") 
     else: 
      output_file.write(line) 

本当に正規表現が必要な場合は、その行のループ内で確認してください。いいえfinditer