CSV尺寸不同的生产线

时间:2019-12-24 12:20:20

标签: python regex

我正在尝试将PDF银行摘录转换为csv。我是python的新手,但是我设法从pdf中提取文本。我以类似以下内容结束:

AMAZON 23/12/2019 15:40 -R $ 100,00 R $ 400,00积分
Some Restaurant 23/12/2019 14:00 -R $ 10,00 R $ 500信用额
从John Doe收到22/12/2019 15:00 R $ 510 R $ 500,00
03游戏22/12/2019 15:00 R $ 10 R $ 10,00借记卡


我想要这个输出:
亚马逊; 23/12/2019; -100,00
一些餐厅; 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()

有人可以给我一些指示吗?

1 个答案:

答案 0 :(得分:0)

尝试使用此split方法。要将字符串分成线并分成单独的部分,然后选择这些部分。

以下链接对此进行了很好的解释。

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")

那应该打印出来。