2022年 11月 8日

python 提取代码中的所有汉字

遇到一个需求,需要提取代码中所有用到的汉字,有lua代码c++代码还有oc代码,于是研究了一个脚本,专门提取代码中的汉字,现在研究好了,在这里贴一下,供大家参考

  1. # -*- coding: UTF-8 -*-
  2. import os
  3. strStr = []
  4. suf_set = ('.lua','.cpp','.h','.hpp','.m','.mm')
  5. isFilterEnglish = 0 #是否过滤英文
  6. #指定目录下 (可修改)
  7. filePathC = "C:\\Users\\panyafei\\Desktop\\test\\src"
  8. #写入指定文件 (可修改)
  9. saveFilePath = 'C:\\Users\\panyafei\\Desktop\\test\\666.txt'
  10. #写入文本名称 (可修改)
  11. saveName = "words.txt" #默认存储文件名
  12. # 遍历指定目录,显示目录下的所有文件名
  13. def eachFile(filepath,saveFilePath):
  14. for root, dirs, files in os.walk(filepath):
  15. for file in files:
  16. luaFileName = os.path.join(root, file)
  17. if luaFileName.endswith(suf_set):
  18. readFile(luaFileName,saveFilePath)
  19. # 保存字符串到文本中
  20. def save_to_file(file_name, contents):
  21. str = ""
  22. content = ""
  23. if isFilterEnglish == 1:
  24. for char in contents:
  25. if ord(char)>=65 and ord(char)<90 or ord(char)>=97 and ord(char)<122:
  26. print("过滤英文")
  27. else:
  28. content = content + char
  29. else:
  30. content = contents
  31. f = open(file_name, 'r')
  32. str = f.read()
  33. f.close()
  34. fh = open(file_name, 'w')
  35. if str == "":
  36. fh.write(str + content)
  37. else:
  38. fh.write(str+ '\n' +content)
  39. fh.close()
  40. # 读取文件内容并打印
  41. def readFile(filename,saveFilePath):
  42. # 搜寻以下文件类型
  43. isPiZS = 0 # 批注释
  44. f = open(filename) # 返回一个文件对象
  45. line = f.readline() # 调用文件的 readline()方法
  46. while line:
  47. line = line.lstrip()
  48. line = line.lstrip('\t')
  49. #print("line = "+line) # 后面跟 ',' 将忽略换行符
  50. l = len(line)
  51. if l>0:
  52. #如果是批注释的话不管是不是中文字符都不管
  53. index = filename.find(".lua")
  54. if judgeIsZhiShiBegan(filename, line):
  55. isPiZS = 1
  56. #如果是批注释中,那么就找到结尾,并且把结尾后的字符截取出来
  57. if isPiZS == 1 :
  58. pos = 0
  59. isfound,pos = judgeIsZhiShiEnd(filename,line)
  60. if isfound == 1:
  61. if pos+2<l-1:
  62. line = line[pos+2:l-1]
  63. else:
  64. line = "\n"
  65. isPiZS = 0
  66. l = len(line)
  67. if judgeIsZhuShi(filename,line) == 1 or line[0] == '\n' or isPiZS != 0 :
  68. print("过滤注释!")
  69. else:
  70. findChinaStr(line,saveFilePath)
  71. line = f.readline()
  72. f.close()
  73. #检测这是否是一个注释行
  74. def judgeIsZhuShi(filename,str):
  75. value = filename.find(".lua")
  76. pos = 0 #表示的是生效开始下表位置
  77. lens = len(str)
  78. isZhuShi = 0
  79. # pp = ord(' ')
  80. for num in range(0,lens-1): # 迭代 0 到 len 之间的数字
  81. if str[num] !=' ':
  82. pos = num
  83. break
  84. if value>0: #lua文件
  85. if str[pos] == '-' and (lens-pos) >= 2 and str[pos+1] == '-':
  86. isZhuShi = 1
  87. else:
  88. if ord(str[pos]) == 47 and (lens-pos) >= 2 and ord(str[pos]) == 47:
  89. isZhuShi = 1
  90. return isZhuShi
  91. #检测批注释的开始
  92. def judgeIsZhiShiBegan(filename,str):
  93. value = filename.find(".lua")
  94. pos = 0 # 表示的是生效开始下表位置
  95. lens = len(str)
  96. isZhuShi = 0
  97. for num in range(0, lens - 1): # 迭代 0 到 len 之间的数字
  98. if str[num] != ' ':
  99. pos = num
  100. break
  101. if value > 0: # lua文件
  102. if str[pos] == '-' and (lens - pos) >= 4 and str[pos+1] == '-' and str[pos+2] == '[' and str[pos+3] == '[':
  103. isZhuShi = 1
  104. else:
  105. if ord(str[pos]) == 47 and (lens - pos) >= 2 and ord(str[pos+1]) == 42:
  106. isZhuShi = 1
  107. return isZhuShi
  108. #检测批注释的结尾
  109. def judgeIsZhiShiEnd(filename,str):
  110. value = filename.find(".lua")
  111. pos = 0 # 表示的是生效开始下表位置
  112. lens = len(str)
  113. isZhuShi = 0
  114. for num in range(0, lens - 1): # 迭代 0 到 len 之间的数字
  115. if str[num] != ' ':
  116. pos = num
  117. break
  118. if value > 0:
  119. if str.find('\]'):
  120. pos = str.find(']')
  121. if pos != -1 and lens >= pos + 2 and str[pos + 1] == ']':
  122. # print('找到结尾的批注释!')
  123. isZhuShi = 1
  124. else:
  125. for num in range(0, lens - 1):
  126. if ord(str[num]) == 42 and num+1<lens and ord(str[num+1]) == 47:
  127. # print('找到结尾的批注释!')
  128. pos = num
  129. isZhuShi = 1
  130. break
  131. return isZhuShi,pos
  132. def findChinaStr(str,saveFilePath):
  133. chinese = ""
  134. dataLen = len(str)
  135. i = 0
  136. while i < dataLen:
  137. value = ord(str[i])
  138. if value == 34 and i + 1 < dataLen:
  139. i = i + 1
  140. while ord(str[i]) != 34 and i + 1 < dataLen:
  141. chinese = chinese + str[i]
  142. i = i + 1
  143. if isCanShow(chinese) == True and isCanSave(chinese)==1:
  144. strStr.append(chinese)
  145. save_to_file(saveFilePath, chinese)
  146. print(chinese.decode('utf-8').encode('gbk'))
  147. chinese = ""
  148. i = i + 1;
  149. def isCanSave(chinese):
  150. for str in strStr:
  151. if str == chinese:
  152. return 0
  153. return 1
  154. # 全部ASCII码,不需要显示
  155. def isCanShow(str):
  156. flag = False
  157. tick = 0
  158. for cha in str:
  159. value = ord(cha)
  160. if value <= 127:
  161. tick = tick + 1
  162. if tick == len(str):
  163. return False
  164. return True
  165. if __name__ == '__main__':
  166. if filePathC == "" or (os.path.exists(filePathC) == False):
  167. str = "未设置路径或者路径不存在,是否默认当前路径,按任意键继续,退出请关闭!"
  168. print(str.decode('utf-8').encode('gbk'))
  169. os.system("pause")
  170. filePathC = os.getcwd()
  171. if saveFilePath == "" :
  172. path = os.path.abspath(os.path.dirname(filePathC))
  173. saveFilePath = path + "\\" + saveName
  174. if os.path.exists(saveFilePath):
  175. print('文件存在,清空内容!')
  176. f = open(saveFilePath, "r+")
  177. f.truncate()
  178. else:
  179. print('文件不存在,创建文件')
  180. file = open(saveFilePath, 'w')
  181. file.close()
  182. eachFile(filePathC,saveFilePath)
  183. print("--------------------finish--------------------")
  184. os.system("pause")

脚本中可以自己设置需要查找的路径和保存文本的名字,如果没有设置路径的话会默认指向当前路径,

同时也支持设置文本类型,暂时支持

'.lua','.cpp','.h','.hpp','.m','.mm'

这六种类型,后期可以自己增加删除文件类型。

isFilterEnglish 可以设置是否过滤中文中间夹杂的英文字符,默认是不过滤的,如有需求可以自行修改 0->表示不过滤   1->表示过滤

还有一点需要说明,就是这个保存的文本类型,我这里写的是.txt格式的,如果你需要的是一个表格形式的文本,那么只要把saveName = “words.txt” 改成 saveName = “words.xls” 或者 saveName = “words.xlsx” 即可。

好了,到这里就结束了,此脚本如有更新,会自动上传更新!