大内高手社区

标题: Python清除html文件中内容的方法 [打印本页]

作者: 程序员007    时间: 2021-9-28 14:59
标题: Python清除html文件中内容的方法
  方法一:


[Python] 纯文本查看 复制代码
In [97]: str_ = ''
    ...: flag = 1
    ...: for ele in test:
    ...:     if ele == "<":
    ...:         flag = 0
    ...:     elif ele == '>':
    ...:         flag = 1
    ...:         continue
    ...:     if flag == 1:
    ...:         str_ += ele
    ...:        
In [98]: str_
Out[98]: 'just for testjust for testtest'
In [99]: str_ = ''
    ...: flag = 1
    ...: for ele in test:
    ...:     if ele == "<":
    ...:         flag = 0
    ...:     elif ele == '>':
    ...:         flag = 1
    ...:         ele = ' '
    ...:     if flag == 1:
    ...:         str_ += ele
    ...:        
In [100]: str_
Out[100]: ' just for test   just for test  test '


  方法二:


[Python] 纯文本查看 复制代码
import re
In [156]: pat = re.compile('(?<=\>).*?(?=\<)')
In [157]: pat.findall(test)
Out[157]: ['just for test', '', '', 'just for test', '', 'test']
In [158]: ''.join(pat.findall(test))
Out[158]: 'just for testjust for testtest'


  方法三:

[Python] 纯文本查看 复制代码
pat = re.compile('>(.*?)<')
''.join(pat.findall(test))


  方法四:

[Python] 纯文本查看 复制代码
In [167]: pat = re.compile('<[^>]+>', re.S)
In [168]: pat.sub('', test)
Out[168]: 'just for testjust for testtest'







欢迎光临 大内高手社区 (https://bbs.tedu.cn/) Powered by Discuz! X3.4