#-*- coding:utf-8-*-
#处理中文字符的情况
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import re
import codecs
# 搜寻以下文件类型
suf_set = ('.h', '.m','.pch')
# 项目路径
# ../文件夹路径
project_path = '/Users/css/Desktop/MIT_IPAD'
strStr = {"中文字符采集",}
for (root, dirs, files) in os.walk(project_path):
for file_name in files:
if file_name.endswith(suf_set):
print('-----fileName-------' + file_name)
with open(os.path.join(root, file_name), 'r+') as f:
print('========fileName========' + file_name)
s0 = f.readlines()
f.close()
for str in s0:
str = str.decode()
str = str.strip()
str = re.sub("\/\*[\s\S]*\*\/|\/\/.*","",str)
str = re.sub("[\u4e00-\u9fa5]", "", str)
str = re.sub("[A-Za-z0-9\!\%\[\]\,\。\(\)\{\}\.\"\'\&\+\-\/\|\~]", "", str)
str = str.replace(' ', '')
str = str.replace('\n', '').replace('\n', '')
if (str.find('//') < 0 and str.find('/*') < 0 and str.find('*') < 0 and str.find('#') < 0 and (str != '\n')):
str = str + '\n'
strStr.add(str)
print ("~~~遍历结束~~~")
list1 = list(strStr)
file_path = os.path.abspath('.') + '/cnStr6.txt'
with codecs.open(file_path, 'a', encoding='utf-8') as f2:
f2.writelines(list1)
f2.close()
提取什么的当然是python方便了,奈何自己菜,所以网上找的大神的代码:
大神地址: https://www.jianshu.com/p/ceff184e7a14
我只加了个忽略注释的正则(还有问题)
背景主要是,项目要做国际化,纯代码中的汉字有很多,手动提取太麻烦,所以想到用 python,
代码我试了,能正确提取大部分文字,也有一些文字被漏提取,弄完需要大家校验,校验方法 就是xcode上的finder -》Regular Expression 中输入
@"[^"]*[\u4E00-\u9FA5]+[^"\n]*?"
使用正则去查询,配合生产的汉字文件,做进一步校验,工作量会少很多,
python的作用是读取文件夹下我们想让他读取的.h.m.pch文件,逐行去提取汉字,用的是re模块的方法,我需要好好研究一些,看来我还是需要继续学学python,还有正则