我正试图建立一个金融仪表板与瓶和pymongo。起点是将数据保存在MongoDB数据库中的烧瓶表单。表单中的一个字段是FileField (Wtform),它允许上传PDF,然后用GridFS存储在MongoDB中。现在,我设法保存了pdf,我可以在.files和.chunks集合中看到结果条目。现在我想构建一个函数来检索PDF并使用一些基本的NLP来分析它们,但是我很难获得有意义的数据。
当我这么做时:
storage = gridfs.GridFS(db, collection)
data = storage.get('some id')
a = data.read()结果是一个二进制文件。如果我继续:
with open(data, 'rb') as f:
b = f.read()结果是"ValueError: embedded null字节“,或者有时是空的”字节字符串“。
在这方面有什么帮助吗?
发布于 2022-05-04 13:37:09
为了跟进上面的内容,我为自己找到了一个解决方案,由两个独立的函数组成:
(1)在上传表单后,在将文件上传到MongoDB之前,我应用了一个基于pdfminer的函数,该函数提取PDF的字符串内容,并使用NLTK将其转换为句子列表。然后,当我想在文件上运行NLP操作时,我将通过.files将这个列表存储在storage.put(file, sent_list = sent_list) #sent_list being the variable name of the list of sentences.中,我只需要从mongodb调用"sent_list“变量。
(2)如果我想在其原始内容中显示所储存的pdf,我会加入以下功能,作为另一条路线。
storage = GridFS(db, collection)
data = storage.get_last_version(filename)
response = make_response(data.read())
extension = data.filename.split('.')[-1]
response.headers['Content-Type'] = f'application/{extension}'
response.headers['Content-Disposition'] = f'inline; filename={data.filename}'
return response(2)将在我的烧瓶应用程序中打开一个新的选项卡,显示原始格式的.pdf文件。
我希望这对将来遇到类似问题的人有所帮助。
https://stackoverflow.com/questions/72092729
复制相似问题