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

示例代码:

import re
def extract_chinese(text):
    # 移除HTML标签
    text_without_html = re.sub(r'<[^>]+>', '', text)
    text_without_styles = re.sub(r'style="[^"]+"', '', text_without_html)
    # 匹配所有汉字字符
    chinese_chars = re.findall(r'[\u4e00-\u9fff\u3000-\u303f]', text_without_html)
    # 将所有匹配的汉字字符连接成一个字符串
    pure_chinese_text = ''.join(chinese_chars)
    return pure_chinese_text

def print_with_newline_on_period(text):
    # 根据句号分割字符串
    sentences = text.split('。')
    for sentence in sentences[:-1]:  # 最后一个句子后面可能没有句号,所以我们排除它
        print(sentence + '。')  # 打印句子和句号
    if sentences[-1]:  # 如果最后一个片段不是空的,就打印它
        print(sentences[-1])

if __name__ == '__main__':


    # 示例文本
    text_to_extract = """
    <div oncontextmenu="return false" class="xe-preview__content forbidden_contextmenu">
    <p style=";font-size: 16px;font-family: 宋体;white-space: normal;text-indent: 32px;line-height: 32px">
    <span style="font-size: 18px;line-height: 36px;color: rgb(63, 63, 63)"><br></span></p>
    <p style=";font-size: 16px;font-family: 宋体;white-space: normal;text-indent: 32px;line-height: 32px">
    <span style="font-size: 18px;line-height: 36px;color: rgb(63, 63, 63)">这一讲是任务管理力的第二个关键知识点:时间管理。</span></p>
    ... (其他文本)
    """

    strs = extract_chinese(text_to_extract)
    print_with_newline_on_period(strs)

结果:

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

猜你喜欢

转载自blog.csdn.net/jacke121/article/details/134623130