天天看点

python 正则匹配汉字、简单读写、打开txt文件 - pu369com

python 正则匹配汉字、简单读写、打开txt文件

win10环境,假设:

    py脚本所在的当前目录下有index.html文件,现在,

    要将index.html 中的汉字提取出来,保存为当前目录下的temp.txt,然后用notepad.txt打开查看。代码:

#coding=utf8
import os,re

with open(\'index.html\', mode=\'r\', encoding=\'UTF-8\') as f:  # 打开文件
    data = f.read()  # 读取文件
    s = re.findall(\'[\u4e00-\u9fa5]\', data)# 匹配所有汉字
    kw = ("".join(s))
    with open(\'temp.txt\', mode=\'w\', encoding=\'UTF-8\') as fw:  # 打开文件
        fw.write(kw)  #写文件
        
path = \'temp.txt\'
win32api.ShellExecute(0, \'open\', \'notepad.exe\', path, \'\', 1)
              

 其中,mode参数为:r 表示 读, w表示 写, a表示 追加写入

打开文档也可用

import webbrowser as web
web.open(\'filepath or url\')      
python 正则匹配汉字、简单读写、打开txt文件 - pu369com