【问题标题】:Iterate through folder, extract text, create single df遍历文件夹,提取文本,创建单个 df
【发布时间】:2019-08-01 02:43:05
【问题描述】:

我正在尝试遍历桌面上一个文件夹中的多个 PDF 文件。我的目标是从这些 PDF 中读取文本(它们都只有一页长),并将每个不同的 PDF 文本放入一个数据框中的新行中。

我尝试循环浏览该文件夹,它可以为我提供该文件夹中所有 PDF 的文本输出(我创建了一个包含两个“测试”PDF 的文件夹,以查看代码是否有效),但它无法将文本连接到一个数据框中。我希望我的代码输出创建一个包含每个 PDF 文本的新行的单个数据框,以便以后可以将其导出到 csv。我得到的输出是两个单独的数据帧,一旦我导出到 csv,就不会将它们的文本传输到 csv 文件中。事实上,我相信我编写的代码会覆盖除最后一个创建的数据帧之外的每个数据帧,因此只生成一个名为“df”的对象。任何帮助将不胜感激,希望这个查询足够清楚,我已经看过相关的线程,但无法找到解决这个确切问题的线程。

rootdir = 'directory file path'
for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            doc = fitz.open(file)
            page = doc[0]
            text = page.getText("text")

            text_list = []                    #create list to store text in

            text_list.append(text)            # append the text to the list
            df = pd.DataFrame(text_list)      #create a df from the list
            df.columns = ['text']

            doc.close()

            print(df)

输出如下:

         text
0  Dummy PDF file\n
                                                text
0   \n \n \n \n \n \nThis is a test PDF document....

【问题讨论】:

标签: python pandas pdf text


【解决方案1】:

虽然这个问题很老了,但让我回答以帮助某人以防他们有类似的问题。

我相信会覆盖除最后一个创建的数据帧之外的所有数据帧

这是因为您在每次迭代中都覆盖了对象 (df) 和列表 (text_list)。例如:

  • df(第 1 次迭代的结果)= df(第 2 次迭代的结果)
  • df(第二次迭代的结果)=df(第三次迭代的结果)
  • df(第 3 次迭代的结果)= df(第 4 次迭代的结果)

依此类推,直到 df 只包含最后一次迭代, 我在这里修复你的代码:

rootdir = 'directory file path'
text_list = [] #create list to store text in

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        doc = fitz.open(file)
        page = doc[0]
        text = page.getText("text")

    text_list.append(text) # append the text to the list
    doc.close()

#create a df from the list and specified the column at once
df = pd.DataFrame(text_list, columns=['text']) 
print(df)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多