我想提取一个文本中除了中文以外的英文,数字,以及各种符号,用以下代码,能把所有的中文提取出来,有没有什么办法能在原文件中将提取出来的这一部分中文去掉剩下英文数字和各种符号,请求各位大佬帮忙,不尽感激。
import re
def open_file(file):
with open(file, 'r') as f:
return f.read()
def find_chinese(file):
pattern = re.compile(r'[^\u4e00-\u9fa5]')
chinese = re.sub(pattern, '', file)
print(chinese)
find_chinese(open_file('F:/compare/http.txt'))
def find_english(file):
pattern = re.compile(r'[\u4e00-\u9fa5]')
english = re.sub(pattern, '', file)
print(english)
import re
def open_file(file):
with open(file, 'r',encoding="utf8") as f:
return f.read()
def find_chinese(file):
pattern = re.compile(r'[^\u4e00-\u9fa5]')
chinese = re.sub(pattern, '', file)
print(chinese)
def find_unchinese(file):
pattern = re.compile(r'[\u4e00-\u9fa5]')
unchinese = re.sub(pattern,"",file)
print(unchinese)
#find_chinese(open_file('F:/compare/http.txt'))
find_unchinese(open_file('F:/compare/http.txt'))
楼上的思路是对的,你的代码是把非中文替换为空,取非中文只要将中文找出来替换为空就可以了。
注意:
打开文件时要用utf8否则会可能会报错。