当前位置:   article > 正文

python 正则表达式提取网页文字_正则表达式获取网页文本

正则表达式获取网页文本

示例代码

  1. import re
  2. def extract_chinese(text):
  3. # 移除HTML标签
  4. text_without_html = re.sub(r'<[^>]+>', '', text)
  5. text_without_styles = re.sub(r'style="[^"]+"', '', text_without_html)
  6. # 匹配所有汉字字符
  7. chinese_chars = re.findall(r'[\u4e00-\u9fff\u3000-\u303f]', text_without_html)
  8. # 将所有匹配的汉字字符连接成一个字符串
  9. pure_chinese_text = ''.join(chinese_chars)
  10. return pure_chinese_text
  11. def print_with_newline_on_period(text):
  12. # 根据句号分割字符串
  13. sentences = text.split('。')
  14. for sentence in sentences[:-1]: # 最后一个句子后面可能没有句号,所以我们排除它
  15. print(sentence + '。') # 打印句子和句号
  16. if sentences[-1]: # 如果最后一个片段不是空的,就打印它
  17. print(sentences[-1])
  18. if __name__ == '__main__':
  19. # 示例文本
  20. text_to_extract = """
  21. <div oncontextmenu="return false" class="xe-preview__content forbidden_contextmenu">
  22. <p style=";font-size: 16px;font-family: 宋体;white-space: normal;text-indent: 32px;line-height: 32px">
  23. <span style="font-size: 18px;line-height: 36px;color: rgb(63, 63, 63)"><br></span></p>
  24. <p style=";font-size: 16px;font-family: 宋体;white-space: normal;text-indent: 32px;line-height: 32px">
  25. <span style="font-size: 18px;line-height: 36px;color: rgb(63, 63, 63)">这一讲是任务管理力的第二个关键知识点:时间管理。</span></p>
  26. ... (其他文本)
  27. """
  28. strs = extract_chinese(text_to_extract)
  29. print_with_newline_on_period(strs)

结果:

这一讲是任务管理力的第二个关键知识点时间管理。
其他文本

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/763116
推荐阅读
相关标签
  

闽ICP备14008679号