美文网首页
python:从字符串/txt文件中提取中文

python:从字符串/txt文件中提取中文

作者: InPieces | 来源:发表于2019-08-07 22:07 被阅读0次

代码:

def to_chinese(str1):#从字符串中提取中文、空格、换行符,返回一个仅含中文、空格、换行符的字符串
    str2=""
    for i in str1:
        if i =="\n" or i==" ":
            str2=str2+i
        else:
            x=len(i.encode())
            if x==3:
                str2=str2+i
    return str2

def txt_to_chinese(path,encoding="UTF-8"):#功能和上一个函数相同,但对象为txt文件,默认编码格式为"UTF-8"
    f=open(path,'r',encoding=encoding)
    text=str(f.read())
    text=to_chinese(text)
    f.close()
    f=open(path,'w',encoding=encoding)
    f.write(text)
    f.close()

txt_to_chinese("E://桌面//1.txt",encoding="ANSI")#需要参数:文件路径,编码方式(默认为"UTF-8")

功能:从字符串(txt文件)中提取中文、空格、换行符,返回一个仅含中文、空格、换行符的字符串(txt文件)
ps:txt文件编码方式查看方法:https://jingyan.baidu.com/article/ff42efa9e04733c19e2202f4.html

相关文章

网友评论

      本文标题:python:从字符串/txt文件中提取中文

      本文链接:https://www.haomeiwen.com/subject/nqlzdctx.html