【问题标题】:Extracting text from OCR image file从 OCR 图像文件中提取文本
【发布时间】:2019-05-01 09:34:29
【问题描述】:

我正在尝试从 OCR 图像中提取几个字段。我正在使用 pytesseract 读取 OCR 图像文件,这按预期工作。

代码:

import pytesseract
from PIL import Image
import re

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract- 
OCR\tesseract.exe"

value = Image.open("ocr.JPG")
text = pytesseract.image_to_string(value)
print(text)

输出:

ALS 1 Emergency Base Rate
Y A0427 RE ABC
Anbulance Mileage Charge

Y A0425 RE ABC
Disposable Supplies
Y A0398 RH ABC

184800230, x

接下来,我必须从文本中提取 A0427 和 A0425.. 但问题是我没有遍历整行.. 它一次只占用一个字符,这就是我的正则表达式不起作用的原因..

代码:

for line in text :
    print(line)
    x= re.findall(r'^A[0-9][0-9][0-9][0-9]', text)
    print(x)

【问题讨论】:

  • 从你的正则表达式中去掉 start ^ 锚。那就是停止比赛。

标签: regex python-3.x python-tesseract


【解决方案1】:

也去掉那个 for 循环,只使用

x= re.findall(r'A[0-9][0-9][0-9][0-9]', text)

没有任何循环。 ('也删除 ^')

【讨论】:

    【解决方案2】:

    text 是一个字符串,Python 使用for-loop 循环遍历字符串时的默认行为是遍历字符(因为字符串基本上是字符列表)。

    要遍历行,首先使用text.splitlines()将文本分成几行:

    for line in text.splitlines() :
        print(line)
        x= re.findall(r'^A[0-9][0-9][0-9][0-9]', text)
        print(x)
    

    编辑:或者使用 Patels 回答一起跳过循环:)

    【讨论】:

      【解决方案3】:

      您的正则表达式中的问题是 start anchor ^ 它期望您的匹配文本 A0425 应该从行首开始,而实际上并非如此,因为您有 Y 和它之前的空格。所以只需从你的正则表达式中删除^,然后你应该得到所有预期的字符串。此外,您可以将其中的四个 [0-9] 更改为 [0-9]{4},您的缩短正则表达式变为,

      A[0-9]{4}
      

      Regex Demo

      你需要像这样修改你当前的代码,

      import pytesseract
      from PIL import Image
      import re
      
      pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract- 
      OCR\tesseract.exe"
      
      value = Image.open("ocr.JPG")
      text = pytesseract.image_to_string(value)
      
      print(re.findall(r'A[0-9]{4}', text))
      

      这应该打印所有匹配项,而无需单独循环成行,

      ['A0427', 'A0425', 'A0398']
      

      【讨论】:

        猜你喜欢
        • 2013-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多