1. 程式人生 > >查找文件中除了註釋以外的中文

查找文件中除了註釋以外的中文

png base elif xls path color earch and lam

在一些需要國際化的項目中,需要找出曾經代碼中的中文替換為其他文字,我這裏提供一種比較粗糙的查找小工具check_zh.py。有能改進的地方請大家指出。

環境是linux,python2.6

代碼如下:

  1 #/usr/bin/env python
  2 #coding:utf-8
  3 
  4 import os,sys
  5 import re
  6 import codecs
  7 reload(sys)
  8 sys.setdefaultencoding(utf8)
  9 
 10 
 11 zhPattern = re.compile(u[\u4e00-\u9fa5]+
) #用於匹配有中文的行 12 file_types = [.pyc,.jpg,.png,.xls,,.svn-base] #默認過濾掉的二進制文件的擴展名 13 choice_tpye_list = [] #輸入要查找的文件格式 14 save_path = ‘‘ #結果保存位置 15 16 17 18 def start(): 19 ‘‘‘ 20 argv[1]:要查詢的文件或目錄的絕對路徑 21 argv[2]:要查詢的文件的格式,輸入*或者不輸入將按默認設置查 22 argv[3]:查詢結果的保存路徑,絕對路徑
23 :return: 24 ‘‘‘ 25 global choice_tpye_list,save_path 26 try: 27 paths = sys.argv[1] 28 print paths,paths 29 except Exception: 30 paths = ‘‘ 31 try: 32 choices = sys.argv[2] 33 print choices, choices 34 if choices ==
*: 35 choices = ‘‘ 36 except Exception: 37 choices = ‘‘ 38 try: 39 save_path = sys.argv[3] 40 print save_path, save_path 41 except Exception: 42 save_path = os.path.join(os.getcwd(),check_zh.txt) 43 choice_types = choices.split(,) 44 if len(choice_types) == 1 and ‘‘ in choice_types: #choice_types可能是[‘‘],其布爾值為True 45 pass 46 else: 47 choice_tpye_list = choice_types 48 path_list = paths.split(,) 49 for path in path_list: 50 checkDIR(path) 51 52 53 def checkDIR(path): 54 ‘‘‘檢查是不是文件,是文件處理,不是則向下查找文件‘‘‘ 55 if os.path.isfile(path): 56 a,b = os.path.splitext(path) # 去除擴展名 57 if choice_tpye_list: 58 if b in choice_tpye_list: #檢查當前文件擴展名是不是指定查詢的擴展名文件 59 checkZh(path) 60 else: 61 if b not in file_types: 62 checkZh(path) 63 64 elif os.path.isdir(path): 65 file_list = os.listdir(path) 66 path_list = map(lambda x: os.path.join(path, x), file_list) # 轉為絕對路徑 67 for item in path_list: 68 checkDIR(item) 69 else: 70 print u---輸入錯誤--- 71 72 def checkZh(file): 73 ‘‘‘查找文件中的中文位置‘‘‘ 74 num = 1 75 all_lis = [] 76 lis = [] 77 with open(file, r) as f: 78 line = f.readline() 79 while line: 80 try: 81 line = line.decode(utf-8) 82 except Exception,e: 83 print e,----,file,---,num,---,line,u---文件可能是個二進制文件 84 85 content_lis = line.split(#) 86 match = zhPattern.search(content_lis[0]) 87 if match: 88 lis = [file, num, line] 89 all_lis.append(lis) 90 line = f.readline() 91 num += 1 92 93 with codecs.open(save_path, a,utf-8) as f: 94 f.write(文件%s的查找結果:\n%file) 95 if all_lis: 96 for itme in all_lis: 97 f.write( %s 第%s行 %s\n % (itme[0],itme[1], itme[2])) 98 else: 99 f.write( 無相關結果\n) 100 101 102 103 104 105 if __name__ == __main__: 106 start() 107 print u***查找結果將在:%s顯示***%save_path

查找文件中除了註釋以外的中文