我正在尝试为我的家人制作一个自动每月费用计算器。这个想法是,每当他们购物时,他们都会拍摄收据照片并将其发送到电子邮件地址。 Python 脚本下载该图片,并使用 Google Vision API 扫描总金额,然后将其写入 .csv 文件供以后使用。 (我还没有制作 csv 的东西,所以现在只是将其保存到 txt 中。)
这是可行的,因为在我的国家,由于法规的原因,收据看起来都一样,但是 Google Vision API 会逐行返回 OCRed 文本。我现在想做的是逐行检查文本中的总金额,总金额始终采用以下格式(数字空格货币),然后检查 OCR 是否搞砸了,例如将“总金额”放在上方或下方实际数字。
我的问题是,如果我在超过 3 个 .txt OCR 数据上运行此脚本,那么它只能获得前 2 个正确的数据,即使我手动检查它们时它们是相同的。如果我对它们一一运行,那么每次都会让它们变得完美。
OCR 数据如下所示:
总金额:
1000 美元
或
1000 美元
总金额:
到目前为止我的代码:
import re
import os
import codecs
for files in os.listdir('texts/'):
filedir="texts/"+str(files)
with codecs.open(filedir,'rb','utf-8') as f:
lines=f.readlines()
lines=[l.strip() for l in lines]
for index,line in enumerate(lines):
match=re.search(r"(\d+) USD",line)
if match:
if lines[index+1].endswith("USD"):
amount=re.sub(r'(\d\s+(\d)',r'\1\2',lines[index])
amount=amount.replace(" USD","")
print(amount)
with open('amount.txt',"a") as data:
data.write(amount)
data.write("\n")
if lines[index-1].endswith("USD"):
amount=re.sub(r'(\d\s+(\d)',r'\1\2',lines[index])
amount=amount.replace(" USD","")
print(amount)
with open('amount.txt',"a") as data:
data.write(amount)
data.write("\n")
最佳答案
Question: checking if line above or below equals to phrase
简化为以下内容:
Assumptions:
- The Amount line has the following format (Numbers space Currency).
- These exact phrase
"Total amount:"
, exists allways in the other line.- The above lines are separated with a blank line.
FILE1 = u"""Total amount:
1000 USD
"""
FILE2 = u"""1000 USD
Total amount:"""
import io
import os
import codecs
total = []
#for files in os.listdir('texts/'):
for files in [FILE1, FILE2]:
# filedir="texts/"+str(files)
# with codecs.open(filedir,'rb','utf-8') as f:
with io.StringIO(files) as f:
v1 = next(f).rstrip()
# eat empty line
next(f)
v2 = next(f).rstrip()
if v1 == 'Total amount:':
total.append(v2.split()[0])
else:
total.append(v1.split()[0])
print(total)
# csv_writer.writerows(total)
Output:
[u'1000', u'1000']
关于Python 检查上面或下面的行是否等于短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522900/