1. 程式人生 > 其它 >python 提取程式碼中的所有漢字

python 提取程式碼中的所有漢字

技術標籤:python

遇到一個需求,需要提取程式碼中所有用到的漢字,有lua程式碼c++程式碼還有oc程式碼,於是研究了一個指令碼,專門提取程式碼中的漢字,現在研究好了,在這裡貼一下,供大家參考

# -*- coding: UTF-8 -*-
import os

strStr = []
suf_set = ('.lua','.cpp','.h','.hpp','.m','.mm')
isFilterEnglish = 0 #是否過濾英文
#指定目錄下 (可修改)
filePathC = "C:\\Users\\panyafei\\Desktop\\test\\src"
#寫入指定檔案 (可修改)
saveFilePath = 'C:\\Users\\panyafei\\Desktop\\test\\666.txt'
#寫入文字名稱 (可修改)
saveName = "words.txt" #預設儲存檔名

# 遍歷指定目錄,顯示目錄下的所有檔名
def eachFile(filepath,saveFilePath):
    for root, dirs, files in os.walk(filepath):
        for file in files:
            luaFileName = os.path.join(root, file)
            if luaFileName.endswith(suf_set):
                readFile(luaFileName,saveFilePath)

# 儲存字串到文字中
def save_to_file(file_name, contents):
    str = ""
    content = ""
    if isFilterEnglish == 1:
        for char in contents:
            if ord(char)>=65 and ord(char)<90 or ord(char)>=97 and ord(char)<122:
                print("過濾英文")
            else:
                content = content + char
    else:
        content = contents

    f = open(file_name, 'r')
    str = f.read()
    f.close()

    fh = open(file_name, 'w')
    if str == "":
        fh.write(str + content)
    else:
        fh.write(str+ '\n' +content)
    fh.close()

# 讀取檔案內容並列印
def readFile(filename,saveFilePath):
    # 搜尋以下檔案型別
    isPiZS = 0  # 批註釋
    f = open(filename)  # 返回一個檔案物件
    line = f.readline()  # 呼叫檔案的 readline()方法
    while line:
        line = line.lstrip()
        line = line.lstrip('\t')
        #print("line = "+line)  # 後面跟 ',' 將忽略換行符
        l = len(line)
        if l>0:
            #如果是批註釋的話不管是不是中文字元都不管
            index = filename.find(".lua")
            if judgeIsZhiShiBegan(filename, line):
                isPiZS = 1

            #如果是批註釋中,那麼就找到結尾,並且把結尾後的字元截取出來
            if isPiZS == 1 :
                pos = 0
                isfound,pos = judgeIsZhiShiEnd(filename,line)
                if isfound == 1:
                    if pos+2<l-1:
                        line = line[pos+2:l-1]
                    else:
                        line = "\n"
                    isPiZS = 0
                    l = len(line)

            if judgeIsZhuShi(filename,line) == 1 or line[0] == '\n' or isPiZS != 0 :
                print("過濾註釋!")
            else:
                findChinaStr(line,saveFilePath)

        line = f.readline()

    f.close()

#檢測這是否是一個註釋行
def judgeIsZhuShi(filename,str):
    value = filename.find(".lua")
    pos = 0 #表示的是生效開始下表位置
    lens = len(str)
    isZhuShi = 0
    # pp = ord(' ')
    for num in range(0,lens-1):  # 迭代 0 到 len 之間的數字
        if str[num] !=' ':
            pos = num
            break
    if value>0: #lua檔案
        if str[pos] == '-' and (lens-pos) >= 2 and str[pos+1] == '-':
            isZhuShi = 1
    else:
        if ord(str[pos]) == 47 and (lens-pos) >= 2 and ord(str[pos]) == 47:
            isZhuShi = 1

    return isZhuShi

#檢測批註釋的開始
def judgeIsZhiShiBegan(filename,str):
    value = filename.find(".lua")
    pos = 0  # 表示的是生效開始下表位置
    lens = len(str)
    isZhuShi = 0
    for num in range(0, lens - 1):  # 迭代 0 到 len 之間的數字
        if str[num] != ' ':
            pos = num
            break
    if value > 0:  # lua檔案
        if str[pos] == '-' and (lens - pos) >= 4 and str[pos+1] == '-' and str[pos+2] == '[' and str[pos+3] == '[':
            isZhuShi = 1
    else:
        if ord(str[pos]) == 47 and (lens - pos) >= 2 and ord(str[pos+1]) == 42:
            isZhuShi = 1

    return isZhuShi

#檢測批註釋的結尾
def judgeIsZhiShiEnd(filename,str):
    value = filename.find(".lua")
    pos = 0  # 表示的是生效開始下表位置
    lens = len(str)
    isZhuShi = 0
    for num in range(0, lens - 1):  # 迭代 0 到 len 之間的數字
        if str[num] != ' ':
            pos = num
            break

    if value > 0:
        if str.find('\]'):
            pos = str.find(']')
            if pos != -1 and lens >= pos + 2 and str[pos + 1] == ']':
                # print('找到結尾的批註釋!')
                isZhuShi = 1
    else:
        for num in range(0, lens - 1):
            if ord(str[num]) == 42 and num+1<lens and ord(str[num+1]) == 47:
                # print('找到結尾的批註釋!')
                pos = num
                isZhuShi = 1
                break

    return isZhuShi,pos

def findChinaStr(str,saveFilePath):
    chinese = ""
    dataLen = len(str)
    i = 0
    while i < dataLen:
        value = ord(str[i])
        if value == 34 and i + 1 < dataLen:
            i = i + 1
            while ord(str[i]) != 34 and i + 1 < dataLen:
                chinese = chinese + str[i]
                i = i + 1
            if isCanShow(chinese) == True and isCanSave(chinese)==1:
                strStr.append(chinese)
                save_to_file(saveFilePath, chinese)
                print(chinese.decode('utf-8').encode('gbk'))
            chinese = ""
        i = i + 1;

def isCanSave(chinese):
    for str in strStr:
        if str == chinese:
            return 0
    return 1


# 全部ASCII碼,不需要顯示
def isCanShow(str):
    flag = False
    tick = 0
    for cha in str:
        value = ord(cha)
        if value <= 127:
            tick = tick + 1
    if tick == len(str):
        return False
    return True

if __name__ == '__main__':
    if filePathC == "" or (os.path.exists(filePathC) == False):
        str = "未設定路徑或者路徑不存在,是否預設當前路徑,按任意鍵繼續,退出請關閉!"
        print(str.decode('utf-8').encode('gbk'))
        os.system("pause")
        filePathC = os.getcwd()

    if saveFilePath == "" :
        path = os.path.abspath(os.path.dirname(filePathC))
        saveFilePath = path + "\\" + saveName

    if os.path.exists(saveFilePath):
        print('檔案存在,清空內容!')
        f = open(saveFilePath, "r+")
        f.truncate()
    else:
        print('檔案不存在,建立檔案')
        file = open(saveFilePath, 'w')
        file.close()

    eachFile(filePathC,saveFilePath)

    print("--------------------finish--------------------")
    os.system("pause")

指令碼中可以自己設定需要查詢的路徑和儲存文字的名字,如果沒有設定路徑的話會預設指向當前路徑,

同時也支援設定文字型別,暫時支援

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

這六種型別,後期可以自己增加刪除檔案型別。

isFilterEnglish 可以設定是否過濾中文中間夾雜的英文字元,預設是不過濾的,如有需求可以自行修改 0->表示不過濾   1->表示過濾

還有一點需要說明,就是這個儲存的文字型別,我這裡寫的是.txt格式的,如果你需要的是一個表格形式的文字,那麼只要把saveName = "words.txt" 改成saveName = "words.xls" 或者saveName = "words.xlsx" 即可。

好了,到這裡就結束了,此指令碼如有更新,會自動上傳更新!