2017-03-17 11 views
0

*または!を削除するプログラムを作成しようとしていました。彼らが上記の文字で始まっていれば、行から。そのため、何かのように:Python 3.5のtxtから特定の文字を削除する

*81 
!81 

がために変更します

81 
81 

これは私が今のよう使っているコードです:しかし

input("Hello") 
with open("Test.txt",'r') as c: 
    lines = c.readlines() 
    c.close() 
with open("Test.txt",'w') as c: 
    c.truncate() 
    for line in lines: 
     if line.startswith("!") or line.startswith("*") == False: 
      c.write(line) 
     if line.startswith("!") or line.startswith("*") == True: 
      new_line = line.translate({ord(c): None for c in '* !'}) 
      print(new_line) 
      c.write(new_line) 

    c.close() 

は、唯一の星になります削除された、これは何が間違っていますか?あなたのブール条件が正しくない

答えて

0

は、あなたはすべての条件での試験を必要とし、より良いまだnot

if not (line.startswith("!") or line.startswith("*")): 
    ... 

を使用し、いっそのこと最初if

if line.startswith("!") == False and line.startswith("*") == False: 
    ... 

かでandを使用し、興味のあるトークンを抽出し、除外リストと照合してください。

with open("Test.txt",'r') as c: 
    lines = c.readlines() 

with open("Test.txt",'w') as c: 
    for line in lines: 
     if line[0] in "*!": 
      line = line[1:] 
     c.write(line) 
正規表現置換を使用しています
0

ソリューション:

import re 

with open("Test.txt",'r+') as c: 
     inp = c.read() 
     out = re.sub(r'^([\*!])(.*)', r'\2', inp, flags=re.MULTILINE) 
     c.seek(0) 
     c.write(out) 
     c.truncate() 

注、上記の正規表現は置き換えられますのみ有数「*」または「!」。したがって、

*!80 
!*80 
**80 

のような文字の組み合わせで始まる行はすべて「*」先頭とを交換するには

!80 
*80 
*80 

に置き換えられます「!」文字で始まる行では、パターンを

に変更します。
'^([\*!]+)(.*)' 
関連する問題