Regular debarking method
# -*- coding: utf-8 -*-
import re
def html_tag_rm(content: str):
dr = re.compile(r'<[^>]+>',re.S)
return dr.sub('',content)
nltk
It’s cumbersome
needs to install nltk, numpy, pyyaml
# -*- coding: utf-8 -*-
import nltk
def html_tag_rm(content: str):
return nltk.clean_html(content)
htmlParser
import re
from sys import stderr
from traceback import print_exc
from HTMLParser import HTMLParser
class _DeHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.__text = []
def handle_data(self, data):
text = data.strip()
if len(text) > 0:
text = re.sub('[ \t\r\n]+', ' ', text)
self.__text.append(text + ' ')
def handle_starttag(self, tag, attrs):
if tag == 'p':
self.__text.append('\n\n')
elif tag == 'br':
self.__text.append('\n')
def handle_startendtag(self, tag, attrs):
if tag == 'br':
self.__text.append('\n\n')
def text(self):
return ''.join(self.__text).strip()
def dehtml(text):
try:
parser = _DeHTMLParser()
parser.feed(text)
parser.close()
return parser.text()
except:
print_exc(file=stderr)
return text
def main():
text = r'''''
<html>
<body>
<b>Project:</b> DeHTML<br>
<b>Description</b>:<br>
This small script is intended to allow conversion from HTML markup to
plain text.
</body>
</html>
'''
print(dehtml(text))
if __name__ == '__main__':
main()
Read More:
- HTML using title attribute to display text with mouse hover
- Refused to apply style from <URL> because its MIME type (‘text/html‘) is not a supported stylesheet
- KeyError: ‘/home/xxx/anaconda3/lib/python3.8/site-packages/parso/python/grammar38.txt‘
- How to convert audio to subtitle (text) with Python?
- After JQ gets the tag element itself, it gets its own HTML text format (find only finds one level of child elements)
- Python: crawler handles strings of XML and HTML
- Error in pyinstall package Python program: jinja2.exceptions.templatenotfound: Chart_ Solution to component.html
- Vscode HTML file auto supplement HTML skeleton failure
- Python implements inserting content in the specified position of text
- python cx_Oracle.DatabaseError: Error while trying to retrieve text for error ORA-01804
- Parsing the difference between “R” and “RB” patterns of text files (Python)
- Has HTML webpack plugin been installed, or error: cannot find module ‘HTML webpack plugin’
- HTML echo error, NPM run build error, HTML path error
- python reads csv file is an error _csv.Error: iterator should return strings, not bytes (did you open the file in text)
- How to use JavaScript in HTML
- How to center the box horizontally and vertically in HTML
- Convert document txt to UNIX code under Linux
- CMake Error: The source directory “/home/Demo1“ does not appear to contain CMakeLists.txt.
- CMake Error: The source directory “*” does not appear to contain CMakeLists.txt.