數據挖掘-語料庫的構建


語料庫:是我們要分析的所有文檔的集合

使用搜狗實驗室提供的語料庫,里面有一個classlist,里面內容是文件的編號及分類名稱

 

1、導入模塊

import os import os.path filePaths=[] #建立一個空的列表來存放語料庫的文件名稱,數組變量 for root,dirs,files in os.walk( "D:\\Python\\Python數據挖掘\\2.1\\SogouC.mini\\Sample"): for name in files: filePaths.append(os.path.join(root,name))

 使用os.walk傳入這個目錄作為參數,遍歷該文件夾下的全部文件,該方法返回一個Truple的數組,第一個root是文件所在目錄,第二個是root文件下的子目錄命名為dirs,第三個root文件下的所有文件命名為files

拼接文件路徑(可解決不同系統下的的文件拼接)

os.path.join(root,name)

 

2、把第一步的文件路徑下的內容讀取到內存中

 

import codecs filePaths=[] fileContents=[] filenames=[] for root,dirs,files in os.walk( "D:\\Python\\Python數據挖掘\\2.1\\SogouC.mini\\Sample"): for name in files: filePaths.append(os.path.join(root,name)) filePath=os.path.join(root,name) f=codecs.open(filePath,"r",encoding="utf-8") fileContent=f.read() #讀取內容后關閉 fileContents.append(fileContent)

 

使用codecs.open(filePath,method,encoding)來打開文件,然后用文件的read()方法

 

3、把讀取到的內容變成一個數據框

import pandas corpos=pandas.DataFrame({ "filePath":filePaths, "fileContent":fileContents, "class":filenames})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM