参加中软的挑战杯竞赛时,原始数据的格式很多,有txt,docx,pdf等等,为了方便处理,需要把其统一转成txt文本文档,本文是将wps文字文件转化为txt的一种方法,可供参考。
使用前,将所有wps文件放到一个文件夹中,运行代码即可。
import os
import chardet
# 自定义的文件夹路径
file_path = r'C:/Users/90882/Desktop/挑战杯数据T20230308/policy'
for root, dirs, files in os.walk(file_path):
for file in files:
if file.endswith(".wps"):
with open(os.path.join(root, file),"rb") as f:
content = f.read()
encoding = chardet.detect(content)["encoding"]
content_str = content.decode(encoding)
with open(os.path.join(root, file[:-4] + ".txt"),"w", encoding="utf-8") as f:
f.write(content_str)
print('完成')