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

更换更换所有领先的“*”和“!”在以字符开头的行上,改变格式为

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