Python 检查上面或下面的行是否等于短语

标签 python ocr

我正在尝试为我的家人制作一个自动每月费用计算器。这个想法是,每当他们购物时,他们都会拍摄收据照片将其发送到电子邮件地址。 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:

  1. The Amount line has the following format (Numbers space Currency).
  2. These exact phrase "Total amount:", exists allways in the other line.
  3. 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/

相关文章:

Python:可以解包元组并在一行中附加到多个列表吗?

image-processing - 对抗锯齿文本进行 OCR

python - Pytesseract 不识别小数点

python - 如何使用 OCR 检测图像中的下标数字?

regex - 如何仅获取 RegEx 的第一个匹配项(UiPath Studio RegEx Based Extractor)

ios4 - 使用 ABBYY OCR SDK 从图像中检索到的坐标不正确

python - numpy - 向量化函数 : apply_over_axes/apply_along_axis

python - 使用python导入url库但出现错误 "request"

tensorflow 中的Python_io

python - 拆分为 n 个字符串时返回字符串的所有可能组合