团队冲刺第二天

excel 转换 为单个 txt

在目前的算法分类中首先是尝试

在一些资源网站寻找的文件

很多是excel word 格式

其中excel格式居多

然后对于文档的操作使用txt操作比较方便

所以当前是excel文档中提取每一篇新闻存入txt文件

首先是excel文档的分析

对于此excel文件是一个sheet表一个类别

其中一行是一则新闻

4列 分别是 编号 标题 类别 内容

其次使用pandas读取excel

读取过程是首先读取sheet个数 然后 逐个遍历

# 使用pandas读取excel
targetfile = "../article/"
# 数据表个数
sheets = [1, 2, 3, 4, 5, 6, 7, 8]
# 遍历每个数据表 并将数据写入txt文件
for sheet in sheets:
data = pd.read_excel('1.xlsx', sheet_name=sheet)
excel2txt(data, targetfile)

建立类别目录然后存入txt文件

如下是一些excel的基本操作

其中对于建立类别目录是根据网上一位大佬的代码

def creatcatesdir(data, target):
# 获取去重后的分类列表
cates = list(data['channelName'].unique())
# 打印类别
print(cates)
# 建立类别文件夹
for cate in cates:
# 拼接子目录路径
final_path = target + cate
try:
os.mkdir(final_path) # 建立目录
except Exception as e:
print(str(e))

然后是一些基本读存数据的操作

def excel2txt(data, target):
# 建立类别目录
creatcatesdir(data, target)
# 逐条获取excel中的内容
for index, row in data.iterrows():
# 文章内容
content = row['content']
# 文件名 -> 文章id
filename = row['id']
# 文章标题
title = row['title']
# 子目录 -> 类别
cate = row['channelName']
# 拼接文件路径
txt_path = target + cate + os.sep
# 将文章内容写入txt
with open(txt_path + str(filename) + ".txt", encoding='utf-8', mode='wt') as f:
f.write(str(title)+str(content))
原文地址:https://www.cnblogs.com/wang2232985989/p/14908583.html