python - 读取多个文本文件扩展名 .pdf、.txt 和 .htm
问题描述
我有一个文件夹,我想从中读取所有文本文件并将它们放入语料库,但是我只能使用 .txt 文件来完成。如何扩展下面的代码以读取 .pdf、.htm 和 .txt 文件?
corpus_raw = u""
for file_name in file_names:
with codecs.open(file_name, "r", "utf-8") as file_name:
corpus_raw += file_name.read()
print("Document is {0} characters long".format(len(corpus_raw)))
print()
例如:
with open ('/data/text_file.txt', "r", encoding = "utf-8") as f:
print(f.read())
读入可以在笔记本上查看的数据。
with open ('/data/text_file.pdf', "r", encoding = "utf-8") as f:
print(f.read())
什么都不读。
解决方案
有两种类型的文件,二进制文件和纯文本文件。一个文件可以有一个或另一个,有时两者都有。
Html 文件是纯文本、人类可读的文件,您可以手动编辑,但 PDF 文件是二进制 + 文本文件,您需要特殊的程序来编辑它们。
如果你想从 pdf 或 html 中阅读,这是可能的。我不确定您是要提取文本还是要提取源代码,所以我将对两者进行解释。
提取文本
对于 html 文件,可以轻松地提取文本。使用webbrowser
,您可以在浏览器中打开文件,然后使用 urllib 提取文本。有关更多信息,请参阅此处的答案: 使用 Python 从 HTML 文件中提取文本
对于 pdf 文件,您可以使用名为 PyPDF2 的 python 模块。使用 pip: 下载它
$ pip install PyPDF2
并开始使用。这是我在互联网上找到的一个简单程序的示例:
import PyPDF2
# creating a pdf file object
pdfFileObj = open('example.pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# printing number of pages in pdf file
print(pdfReader.numPages)
# creating a page object
pageObj = pdfReader.getPage(0)
# extracting text from page
print(pageObj.extractText())
# closing the pdf file object
pdfFileObj.close()
提取源代码
最好使用 python 的open
函数来提取源代码,就像上面所做的那样。对于 html 文件,您可以执行对文本文件所做的操作。或者也许更简单,
file = open("c:\\path\\to\\file")
print(file.read())
你可以做到以上。
对于 pdf 文件,您所做的几乎相同,但在open
函数的不同参数中指定编辑模式。如需更多信息,请访问“更多信息”部分中的网站。
file = open("c:\\path\\to\\file.extension", "a") #specifies the mode of editing. Unfortunately, you'll only be able to store data, not display it. But you can edit it, then save it after wards
print(file.readable()) #Will return false, proving to be not readable.
file.save("c:\\path\\to\\save\\in.extension")
更多信息
推荐阅读
- powershell - 将文件复制到远程位置,并在名称中添加随机数
- html - 引导 img 不透明度
- python - 如何更正不可调用的 str?
- node.js - 如何测量在 node.js 中开始服务请求所需的时间
- encoding - 使用固定块大小解码任意长度值?
- python - 如何使用 pandas python 从列表中完全删除重复的字符串?
- webpack - 为什么使用多页 webpack 时非 index.html 页面不渲染并做出反应
- javascript - 哪一个合适?在 HTML 中形成“onsubmit”?
- google-sheets - 当谷歌表格中的公式为真时如何输出文本
- postgresql - Pgpool 在集群中添加第二个节点