赞
踩
项目需要对一些如doc、docx、txt等常见格式的文件进行分词处理,之前只用Python的jieba库进行过简单的中文分词,效果不错,但是只能读取txt文件,功能受限。今天查阅了一些论坛,将doc转换为docx,成功读取docx文件并分词,并解决了txt读取的非法字符问题(docx和doc的暂未解决)三个地方。
下面将分别介绍三者如何实现。
- stop_words = open('stopwords1893.txt')
- stop_words_text = stop_words.read()
-
- stop_words.close()
-
- stop_words_text_list = stop_words_text.split('\n')
- for i in range(len(stop_words_text_list)):
- stop_words_text_list[i]=stop_words_text_list[i].strip()
- def readDocument(strFile):
- '''
- 获取文档对象,将文档内容按段落读入,并存入doc中
- '''
- file = docx.Document(strFile)
- doc = ""
- for para in file.paragraphs:
- doc = doc + para.text
- return doc
读取txt中内容
- def readTxt(strFile):
- file=open(strFile,errors="ignore").read()
- txt=file
- return txt
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。