2017-03-17 77 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

你的布爾條件是不正確的,你需要的所有條件的考驗,並在第一if

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

或使用and更好,但使用not

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

和甚至更好,提取您感興趣的令牌並在排除列表中檢查該令牌

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 

更換更換所有領先的「*」和「!」在以字符開頭的行上,改變格式爲

'^([\*!]+)(.*)'