正则匹配提取文档各级标题--标题提取

这里写自定义目录标题

主要目的

从政府报告等文档中直接提取标题复制到xmind思维导图中
修改list勾选标题格式

遇到的问题

exec内的赋值是局部变量
中文标点需要单独转码匹配

源代码

import re

def pattern1(string):
    global tmp
    #patterns =re.compile(r'[\u4e00-\u9fa5]')
    patterns=re.compile(r"[一二三四五六七八九十]+、[\u4e00-\u9fa5\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b\w]+")
    tmp=re.match(patterns,string,0)
    if tmp==None:
        return tmp
    else:
        tmp = tmp.group(0)
        return
def pattern2(string):
    global tmp
    pattern=re.compile(r"[\((][一二三四五六七八九十]+[\))][\u4e00-\u9fa5\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b\w]+?\u3002")
    tmp=re.match(pattern,string,0)
    if tmp==None:
        return tmp
    else:
        tmp = tmp.group(0)
        return
def pattern3(string):
    global tmp
    pattern=re.compile(r"\d+[、.][\u4e00-\u9fa5\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b\w]+?\u3002")
    tmp=re.match(pattern,string,0)
    if tmp==None:
        return tmp
    else:
        tmp = tmp.group(0)
        return

def check(string):
    global tmp
    list=[1,2,3]
    for l in list:
        exec(f'pattern{l}(string)')
        if tmp!=None:
            print(tmp)
            return tmp
    return None

path=r'E:\huang\Desktop\AAA粘贴处理.txt'
output=r'E:\huang\Desktop\BBB标题输出.txt'
file=open(output,'w',encoding='ansi')
with open(path,'r') as f:
    for line in f.readlines():
        l=check(line.strip())
        if l!=None:
            file.write(l.strip()+'\n')
file.close()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

圣道寺

您的支持将使我的探索更进一步

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值