上一篇文章讲了如何使用os
模块读取文件路径,本篇文章讲述如何在读取文件路径时将文件内容进行读取(使用codesc
模块),并最终组成一个数据框作为语料库(使用pandas
模块)。
示例数据为Sogou实验室提供的语料数据,下载地址如下:
链接: https://pan.baidu.com/s/1vtHxR4zuEiGd3ot_wj4oeQ 提取码: sh7y
一、完整示例
将文件路径及内容读取存入变量filePaths和fileContents中,并生成数据框DataFrame。
import os
import os.path#读取文件路径
import codecs#转换文件读取格式
import pandas
filePaths = []#设置存储文件路径的变量
fileContents = []#存储文件内容的变量
for root, dirs, files in os.walk(
"D:\SogouC.mini\Sample"):
#os.walk()返回文件的目录,子目录,文件名,详情见上篇
for name in files:
filePath = os.path.join(root, name)#将目录和子目录拼接为目前的文件路径
filePaths.append(filePath)#将文件路径存入路径变量
f = codecs.open(filePath, "r", "utf-8")#以utf-8的格式打开当前路径下的文件
fileContent = f.read()#读取文件内容
f.close()#关闭文件
fileContents.append(fileContent)#将文件内容存入内容变量
#将文件路径和内容存入DataFrame中
corpos=pandas.DataFrame({
"filePath":filePaths,
"fileContent":fileContents
}
)
输出DataFrame
二、codecs模块
三、课题作业
答案:
import os
import os.path
import codecs
import pandas
fileClass=[]
filePaths=[]
fileContents=[]
for root,dirs,files in os.walk( "D:\SogouC.mini\Sample"):
for name in files:
fileClass.append(root[-7:])
filepath=os.path.join(root,name)
filePaths.append(filepath)
f=codecs.open(filepath,"r","utf-8")
filecontent=f.read()
f.close()
fileContents.append(filecontent)
corcs=pandas.DataFrame({
"fileClass":fileClass,
"filesPath":filePaths,
"fileContent":fileContents
}
输出DataFrame