Corpus: is a collection of all the documents we want to analyze
Use Sogou Lab provided corpus, there is a classlist, inside the content is the document number and classification name
1. Import Module
Import OS Import os.pathfilepaths=[] #建立一个空的列表来存放语料库的文件名称, array variable for in os.walk ( "d:\\python\\python Data Mining \\2.1\\SogouC.mini\\Sample"): for inch files: filepaths.append (Os.path.join (root,name))
use Os.walk to pass in this directory as a parameter, traverse all the files under the folder, the method returns an array of Truple, the first root is the directory where the file is located, the second is the root file under the name dirs, all the files under the third root file are named files
Stitching file path (to resolve file concatenation under different systems)
Os.path.join (Root,name)
2, the first step of the file path under the contents of the read into memory
Importcodecsfilepaths=[]filecontents=[]filenames=[] forRoot,dirs,filesinchOs.walk ("D:\\python\\python Data Mining \\2.1\\SogouC.mini\\Sample"): forNameinchfiles: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)
Use Codecs.open (filepath,method,encoding) to open the file and then use the Read () method of the file
3. Turn the read content into a data frame
Import Pandascorpos=pandas. DataFrame ({ "filePath": filepaths, " Filecontent": filecontents, "class": Filenames })
Data Mining-Corpus construction