Python:从URL中的Word文件中提取文本
问题描述:
如果URL包含某个文件(在本例中为word文档),请阅读文档的内容。我已经看到了几个如何从本地文档中提取文本的例子,但没有从网址中提取文本。从一个http地址比从一个ftp是否是相同的?Python:从URL中的Word文件中提取文本
from urllib.request import urlopen
url = 'ftp://path/to/file.docx'
txt = urlopen(url).read()
文本的价值是:
b'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x00\xdd\xfc\x957f\x01\x00\x00 \x05\x00\x00\x13\x00\x08\x02[Content_Types].xml \xa2\x04\x02(\xa0\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 ...'
我尝试解码
txt.decode("utf-8", "ignore")
但这返回PK ...
其次是其他奇怪的字符
保存文档的选项然后处理它是不可行的。
我在做什么错?
答
我终于找到了一个解决方案,我希望有人可以帮助
from urllib.request import urlopen
from bs4 import BeautifulSoup
from io import BytesIO
from zipfile import ZipFile
file = urlopen(url).read()
file = BytesIO(file)
document = ZipFile(file)
content = document.read('word/document.xml')
word_obj = BeautifulSoup(content.decode('utf-8'))
text_document = word_obj.findAll('w:t')
for t in text_document:
print(t.text)
使用urlib2这是它做什么。 :)我认为现在有一个lib3。 – Rob
https://docs.python.org/3.6/library/urllib.request.html#module-urllib.request –
您可以使用urlib2从该URL下载文件,并将其保存在本地,最后从中提取数据它为本地文件 –