用Python遍歷資料夾下所有電子字典檔案(不包括子資料夾)提取單詞到一個檔案
阿新 • • 發佈:2018-12-13
經過若干天的嘗試,最後凝鍊出了這麼一段程式碼,集幾天研究之成果,可謂費盡心機。裡面用到的成果包括:
1.with open...as
2.處理有亂碼的文字
於是趕緊先寫下來,做個階段性成果。
import re import os.path p=re.compile(r"\b[a-z]{2,40}\s?\r\n")#單詞(2-40個字母以內)單詞後回車前可能有0或者1個空格,所以用了“\s?” filedir=r"B" filenames=os.listdir(filedir) with open("allwords.txt","w") as f: for filename in filenames: filepath=filedir+"\\"+filename with open(filepath,"rb") as fr: #只能用“rb”,以二進位制形式開啟 str=fr.read().decode("gbk","ignore")#解碼,必須加上"ignore",這裡有大坑。 words=re.findall(p,str) for word in words: f.write(word)