行走目录时字数统计PDF文件

问题描述 投票:1回答:1

你好Stackoverflow社区!

我正在尝试构建一个Python程序,它将遍历一个目录(和所有子目录),并对所有.html,.txt和.pdf文件执行累计字数统计。在读取.pdf文件时,需要一些额外的(PdfFileReader)来解析文件。解析.pdf文件时,我收到以下错误,程序停止:

AttributeError:'PdfFileReader'对象没有属性'startswith'

如果不解析.pdf文件就完全成功了。

CODE

#!/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])

The full error

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文件调用提取函数时似乎出现故障。任何帮助/指导将不胜感激!

Expected Results (works w/out .pdf files)

[('cyber', 5101), ('2016', 5095), ('date', 4912), ('threat', 4343)]
python pdf word-count os.walk pdf-reader
1个回答
0
投票

问题是这一行

reader = PdfFileReader(f)

返回PdfFileReader类型的对象。然后,您将此对象传递给extract()函数,该函数需要文件路径而不是PdfFileReader对象。

建议将您在search()函数中当前具有的PDF相关处理移动到提取函数()。然后,在提取功能中,您将检查它是否是PDF文件,然后相应地采取行动。所以,像这样:

def extract(file_path, counter):
    if file_path.lower().endswith(('.pdf')):
        reader = PdfFileReader(file)
        contents = reader.getPage(0).extractText().split('\n')
        counter.update([x for x in contents if x not in ignore and len(x) > 2])
    elif file_path.lower().endswith(('.html', '.txt')):
        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])
    else:
        ## some other file type...

还没有测试过上面的代码片段,但希望你能得到这个想法。

© www.soinside.com 2019 - 2024. All rights reserved.