python - 如何检查从图像中提取的值是否已存在于Python中的txt或csv文件中?

标签 python ocr tesseract file-handling python-tesseract

我正在使用 python 和 pytesseract 进行 OCR 工作。所以我想做的就是读取图像上的文本,提取文本并使用文件处理将提取的文本存储在 txt 或 csv 文件中。 我想要读取多个文件,存储文本并检查要读取和存储的图像文本是否已存在于 txt 文件中。
这是我的代码,运行时没有任何错误。最后几行是我试图做的,但似乎不起作用。有人可以帮我解决这个问题吗? 提前致谢。

import cv2
import pytesseract,csv,re,os
from PIL import Image
from ast import literal_eval

img = pytesseract.image_to_string(Image.open("test1.png"), lang="eng")
print(img)

with open('C:\\Users\\Hasan\\Videos\\Captures\\saved.csv', "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(img)

string = open('C:\\Users\\Hasan\\Videos\\Captures\\saved.csv').read()
new_str = re.sub('[^a-zA-z0-9\n\.]', ' ', string)
open('C:\\Users\\Hasan\\Videos\\Captures\\saved.csv', "w").write(new_str)

# f = open("saved.csv", "r")
# read = f.readline()
# print("\n" + f.read())

with open('C:\\Users\\Hasan\\Videos\\Captures\\saved.csv') as sv:
    for line in sv:
        if img in line:
            print("Data already exists")
        else:
            print("file saved successfully")

最佳答案

写入 CSV 文件时替换“\n”,并在比较时从 img 中删除“\n”。

import cv2
import pytesseract,csv,re,os
from PIL import Image
from ast import literal_eval
img_path = "example_01.png"
out_csv_path = "saved.csv"
img = pytesseract.image_to_string(Image.open(img_path), lang="eng")
print(img)

with open(out_csv_path, "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(img)

string = open(out_csv_path).read()
new_str = re.sub('[^a-zA-z0-9\. ]', '', string)
open(out_csv_path, "w").write(new_str)

# f = open("saved.csv", "r")
# read = f.readline()
# print("\n" + f.read())

with open(out_csv_path,newline='') as sv:
    img = re.sub('[^a-zA-z0-9\. ]', '', img)
    for line in sv:
        print("Line text is: {}\nExtracted Text is: {}".format(line,img))
        if img in line:
            print("Data already exists")
        else:
            print("file saved successfully")

示例输出:

Noisyimage
to test
Tesseract OCR
Line text is: Noisyimageto testTesseract OCR
Extracted Text is: Noisyimageto testTesseract OCR
Data already exists

关于python - 如何检查从图像中提取的值是否已存在于Python中的txt或csv文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58619861/

相关文章:

Python:通过函数传递memmap数组?

python - 在matplotlib python中找到对应于y轴的x轴值

python - Tkinter Canvas Sense Touch?

c# - 将金额字符串解析为数字

android - tesseract v3.03 渲染带有可搜索文本示例的 PDF

python - 是否可以在没有 Visual Studio 许可证的情况下在 Windows 上编译 Cython 模块用于商业目的?有哪些替代方案?

c++ - Tesseract 虚假空间识别

c# OCR 无法识别数字(tesseract 2)

java - 未进入 tessract 方法 doOCR(File imageFile) 内部

java - 如何使用 Tesseract 提高 OCR 质量?