Hello Stackoverflow社区!
我正在尝试构建一个Python程序,它将遍历一个目录(和所有子目录)并对所有.html,.txt和.pdf文件执行累计字数统计 . 在读取.pdf文件时,需要一些额外的(PdfFileReader)来解析文件 . 解析.pdf文件时,我收到以下错误,程序停止:
AttributeError:'PdfFileReader'对象没有属性'startswith'
如果不解析.pdf文件就完全成功了 .
代码
#!/usr/bin/python
import re
import os
import sys
import os.path
import fnmatch
import collections
from PyPDF2 import PdfFileReader
ignore = [<lots of words>]
def extract(file_path, counter):
words = re.findall('\w+', open(file_path).read().lower())
counter.update([x for x in words if x not in ignore and len(x) > 2])
def search(path):
print path
counter = collections.Counter()
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for file in files:
if file.lower().endswith(('.html', '.txt')):
print file
extract(os.path.join(root, file), counter)
if file.lower().endswith(('.pdf')):
file_path = os.path.abspath(os.path.join(root, file))
print file_path
with open(file_path, 'rb') as f:
reader = PdfFileReader(f)
extract(os.path.join(root, reader), counter)
contents = reader.getPage(0).extractText().split('\n')
extract(os.path.join(root, contents), counter)
pass
else:
extract(path, counter)
print(counter.most_common(50))
search(sys.argv[1])
完整错误
Traceback (most recent call last):File line 50, in <module> search(sys.argv[1])
File line 36, in search extract(os.path.join(root, reader), counter)
File line 68, in join if b.startswith('/'):
AttributeError: 'PdfFileReader' object has no attribute 'startswith'
使用.pdf文件调用提取函数时似乎出现故障 . 任何帮助/指导将不胜感激!
预期结果(工作w / out .pdf文件)
[('cyber', 5101), ('2016', 5095), ('date', 4912), ('threat', 4343)]
1 回答
问题在于这一行
返回PdfFileReader类型的对象 . 然后,您将此对象传递给extract()函数,该函数需要文件路径而不是PdfFileReader对象 .
建议将您在search()函数中当前具有的PDF相关处理移动到提取函数() . 然后,在提取功能中,您将检查它是否是PDF文件,然后相应地采取行动 . 所以,像这样:
还没有测试过上面的代码片段,但希望你能得到这个想法 .