首页 > 解决方案 > 从 PDF 中提取文本 -Tokenize TypeError

问题描述

当尝试使用 Textract 从 PDF 中提取文本时,我得到一个 TypeError:“不能在类似字节的对象上使用字符串模式”。任何人都可以对可能的解决方案有所帮助吗?当我打印(文本)时,我从要提取的 PDF 中获取文本,尽管格式有点奇怪。但是, text[0] 等只包含数字..?

import textract
import os
from nltk.tokenize import word_tokenize

for filename in os.listdir('Harbour PDF'):
if '.DS_Store' == filename:
    continue
filename = 'Harbour PDF/' + filename
print(filename)

text = textract.process(filename)
print(text)

tokens = word_tokenize(text)
keywords = [word for word in word_tokenize(text,'english',False)]

错误:

文件“scrapePort.py”,第 15 行,在 tokens = word_tokenize(text) 文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/init .py ”,第 143 行,在 word_tokenize sentence = [text] if preserve_line else sent_tokenize(text, language) File " /Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/init.py”,第 105 行,在 sent_tokenize 返回 tokenizer.tokenize(text) 文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py”,第 1269 行,在 tokenize 返回list(self.sentences_from_text(text, realign_boundaries)) 文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py”,第 1323 行,在 sentence_from_text 中返回 [text[s: e] for s, e in self.span_tokenize(text, realign_boundaries)] 文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py”,第 1323 行,作为回报 [ text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] 文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py”,第 1313 行, 在 span_tokenize 中用于切片中的 sl:文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py”,第 1354 行,在 _realign_boundaries 中,用于 _pair_iter(切片)中的 sl1、sl2:文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk /tokenize/punkt.py”,第 317 行,在 _pair_iter prev = next(it) 文件“/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py”,第 1327 行,在 _slices_from_text 中匹配 self._lang_vars.period_context_re().finditer(text):_lang_vars.period_context_re().finditer(text):_lang_vars.period_context_re().finditer(text): TypeError:不能在类似字节的对象上使用字符串模式

标签: pythonpdfextract

解决方案


我遇到了同样的问题,试试这个

 tokens = word_tokenize(text.decode("utf-8"))

推荐阅读