【Python数据挖掘入门】2.1 文本分析-语料库文件路径及内容读取(codesc&pandas模块)

上一篇文章讲了如何使用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
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值