import re
import pdfplumber
import pandas as pd
from collections import namedtuple
path = r"C:\Users\x\Documents\Python Scripts\Files\x.pdf"
Line = namedtuple('Line', 'print_date order_no pos item_no issue qty UM price req_date line_amt')
with pdfp.open(path) as pdf:
page = pdf.pages[2]
text = page.extract_text()
new_vend_re = re.compile(r'^\d{1,}\s[A-Z].*')
for line in text.split('\n'):
if new_vend_re.match(line):
print(line)
這會找到并列印如下內容:
53 AB839-11 0002 31.00 EA 58.5300 1814.43
有些頁面和頁面必須提取類似的值。這只是一個例子。進行處理的剩余代碼:
line_items = []
with pdfplumber.open(path) as pdf:
pages = pdf.pages
for page in pdf.pages:
text = page.extract_text()
for line in text.split('\n'):
line = new_vend_re.search(line)
if line:
pos = line.group(1)
item_no = line.group(2)
issue = line.group(3)
qty = line.group(4)
UM = line.group(5)
price = line.group(6)
amt = line.group(7)
line_items.append(Inv(pos, item_no, issue, qty, UM, price, amt))
df = pd.DataFrame(line_items)
df.head()
我有這段代碼,但它似乎無法將提取的資料放入各自的元組中。我的程式基本上應該遍歷具有多個頁面的 PDF,并準確地從正則運算式運算式中提取的各種專案中獲取值并將它們放入元組中,但我的代碼由于某種原因不起作用。
uj5u.com熱心網友回復:
您的正則運算式錯誤 - 它以"^\d "- 開頭,表示行首后跟數字。檔案中的行以"(......)"- 更改正則運算式開頭:
import re
from collections import namedtuple
Inv = namedtuple('Inv', 'pos, item_no, issue, qty, UM, price, amt')
new_vend_re = re.compile(r'\d \s[A-Z].*')
text = "some\nmore (53 AB839-11 0002 31.00 EA 58.5300 1814.43) things \ntext\n"
line_items = []
for line in text.split('\n'):
searched = new_vend_re.search(line)
if searched:
print(line)
# get the matched part of the line and remove ( ) from start/end
m = searched.group(0).strip("()")
# now its as simple as splitting it into variables
pos, item_no, issue, qty, UM, price, amt, *crap = m.split()
# and use a namedtuple that works with that amount of data
line_items.append(Inv(pos, item_no, issue, qty, UM, price, amt))
if crap:
print(crap, "that was also captured but not used")
print(*line_items)
import pandas as pd
df = pd.DataFrame(line_items)
print(df.head())
輸出:
# line
more (53 AB839-11 0002 31.00 EA 58.5300 1814.43) things
# crap catchall
['things'] that was also captured but not used
# named tuple
Inv(pos='53', item_no='AB839-11', issue='0002', qty='31.00', UM='EA', price='58.5300', amt='1814.43)')
# df
pos item_no issue qty UM price amt
0 53 AB839-11 0002 31.00 EA 58.5300 1814.43)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/464237.html
上一篇:Excel-如何在另一個電子表格的單元格中根據手動選擇的顏色(不基于單元格值)設定單元格顏色
下一篇:在多列上將垂直轉換為水平
