# coding = utf-8 import os import xlwt import re def readTxt_toExcel(valueList, Pathlist): workbook = xlwt.Workbook() # sheet = workbook.add_sheet('finish_鄭磊', cell_overwrite_ok=True) # Excel單元格名字 style = xlwt.XFStyle() font = xlwt.Font() font.name = 'Times New Roman' font.bold = True # 設置樣式的字體 style.font = font title = ["Filepath", "Rect", "右眉毛屬性", "右眼屬性", "右瞳孔屬性", "嘴巴屬性", "左眉毛屬性", "左眼屬性", "左瞳孔屬性", "臉頰屬性", "表情屬性", "鼻子屬性"] '''寫入title 信息''' col = 0 # 控制列 for head in title: sheet.write(0, col, head, style) col += 1 '''寫入 value值以及文件名''' hang = 1 for i in valueList: lie = 0 for value in i: sheet.write(hang, lie, value) lie += 1 hang += 1 h = 1 for j in Pathlist: end_name = j.rfind('.') path = str(j[:end_name]) sheet.write(h, 0, path) # 導入文件地址 h += 1 workbook.save("C:\\Users\\zl3269.ARCSOFT-HZ\\Desktop\\finish_鄭磊.xls") def get_txt_content(file_path): # 獲取文件內容 Pathlist = [] # 添加文件名列表 valueList = [] # value 列表 num = 1 for path, d, file_list in os.walk(file_path): # path 原路徑下的文件遍歷 flie_list 文件下的所有文件 print(path) for filename in file_list: if filename.endswith(".txt"): with open(path+"\\"+filename, 'r', encoding="utf-8") as f: # 打開文件 文本的全部路徑 Pathlist.append(filename) # 將文件地址添加到列表里 # print(txt) items = f.readlines() # 讀取文件,列表格式 pattern = re.compile( '.*?name":"(.*?)".*?rect":"(.*?)".*?右眉":"(.*?)".*?右眼":"(.*?)".*?右瞳孔":"(.*?)".*?嘴巴":"(.*?)".*?左眉":"(.*?)"' '.*?左眼":"(.*?)".*?左瞳孔":"(.*?)".*?臉頰":"(.*?)".*?表情":"(.*?)".*?鼻子":"(.*?)"') value = (re.findall(pattern, items[0])) # 正則匹配需要的字符串 # print(type(value)) #[("":"")] 這種類型,所以下面用value[0]獲得("":"")並添加到列表,用兩個循環調通里面的值 # print(value[0]) valueList.append(value[0]) num += 1 print("已處理文件:" + str(num)) readTxt_toExcel(valueList, Pathlist) # 處理txt文件 def main(): file_path = "F:\\人臉標注\\test_new_20171005\\" get_txt_content(file_path) if __name__ == '__main__': main()