removing tag from a line in Python

后端 未结 3 1820
感动是毒
感动是毒 2021-01-28 02:41

I have a text that has the following schema:

word1:word2
word3:word4
...

I would like to remove the last part
, a

相关标签:
3条回答
  • 2021-01-28 02:47

    That's because each line ends with newline character(s).

    You can fix it like this (and automatically close the file):

    def main():
        with open("test.txt", "r") as fileR:
            for line in (line.rstrip() for line in fileR):
                if line.endswith('<br />'):
                    line = line[:-6]
                    print line
    
    0 讨论(0)
  • 2021-01-28 02:56

    I'd recommend using a regex replace for this instead of what you're currently using.

    import re
    
    def main():
      fileR=open('test.txt','r')
      for line in fileR:
        line = re.replace(r'<br ?/>$','',line)
        print line
    

    Or, if you want, you can just replace all of them at once before printing out each line individually because python's regex is global by default.

    import re
    
    def main():
      fileR=open('test.txt','r')
      fileR = re.replace(r'<br ?/>$','',fileR)
      for line in fileR:
        print line
    
    0 讨论(0)
  • 2021-01-28 02:58

    You can use a regular expression:

    import re
    re.sub('<br>', '', line)
    

    For example:

    re.sub('<br>', '', 'test<br>text<br>')
    

    gives:

    testtext
    
    0 讨论(0)
提交回复
热议问题