首页 > 解决方案 > 不同大小的工艺线到csv

问题描述

我正在尝试将 PDF 银行提取转换为 csv。我对python相当陌生,但我设法从pdf中提取文本。我以与此类似的内容结束:

亚马逊 23/12/2019 15:40 -R$ 100,00 R$ 400,00 credit
一些餐厅 23/12/2019 14:00 -R$ 10,00 R$ 500 credit
从 John Doe 22/12/2019 收到15:00 R$ 510 R$ 500,00
03 Games 22/12/2019 15:00 R$ 10 R$ 10,00 debit


我想要这个输出:
AMAZON;23/12/2019;-100,00
Some Restaurant; 23/12/2019;-10,00
从 John Doe 收到;22/12/2019;510
03 游戏;22/12/2019;10

第一个字段有不同的大小,我不需要时间和货币格式。我不需要最后两个字段。

到目前为止我有这段代码(只是从 PDF 中提取文本):

import pdfplumber
import sys

url = sys.argv[1]
pdf = pdfplumber.open(url)
pdf_pages = len(pdf.pages)

for i in range(pdf_pages):
    page = pdf.pages[(i)]
    text = page.extract_text()
    print(text)
pdf.close()

任何人都可以给一些指示吗?

标签: pythonregex

解决方案


尝试使用这种拆分方法。将字符串分成几行并分成单独的部分,然后选择这些部分。

以下链接很好地解释了它。

https://www.w3schools.com/python/showpython.asp?filename=demo_ref_string_split

lines:List[str] = text.split("\n")
for line in lines:
    entries:List[str] = line.split()
    date_entry_index: int = get_date_index(entries)
    name = entries[0]
    for index in range(1, date_entry_index + 1):
        name += " " + entries[index]
    print(f"{name};{entries[date_entry_index]};{entries[date_entry_index + 2]}")

def get_date_index(entries_check:List[str]) -> int:
    # either you could use the function below or you check if the entry only contains digits and "/"
    for index, entry in enumerate(entries):
        if len(entry) == 10:
            continue
        if entry[2] != "/" or entry[5] != "/":
            continue
        # here you could check if the other parts of the date are digits or some letters or something similar.
        return index
    else:
        raise ValueError("No Date found")

那应该打印它。


推荐阅读