检查字符串是否为九位数,然后退出python中的函数

2024-05-23 14:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个函数,它返回字符串(文本)的不同输出。我有不同的部分,我应该检查字符串,如果字符串是9位数字或包含9位数字,那么我需要在函数中执行,以在该点退出函数 我是python的新手,如果达到标准,我不知道如何在特定点退出函数。 比如说

s = 'oodf 191876320x sd'
print(any(char.isdigit() for char in s))

这将检查字符串是否有数字。我需要添加另一个标准,以确保有相邻的9个数字。如果True,则在该点退出该函数

我正在处理的代码是从图像中读取数字(有三种不同的操作情况) 这是我的尝试,我欢迎任何想法

import pytesseract, cv2, re

def readNumber(img):
    img = cv2.imread(img)
    gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    txt = pytesseract.image_to_string(gry)
    if bool(re.search(r'\d{9}', txt)):
        return re.findall('(\d{9})\D', txt)[0]
    blur = cv2.GaussianBlur(img, (3,3), 0)
    txt = pytesseract.image_to_string(blur)
    if bool(re.search(r'\d{9}', txt)):
        return re.findall('(\d{9})\D', txt)[0]
    thr = cv2.adaptiveThreshold(gry, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 4)
    txt = pytesseract.image_to_string(thr, config="digits")
    if bool(re.search(r'\d{9}', txt)):
        return re.findall('(\d{9})\D', txt)[0]
    '''
    
    try:
        txt = pytesseract.image_to_string(gry)
        #txt  = re.findall('(\d{9})\D', txt)[0]
    except:
        thr = cv2.adaptiveThreshold(gry, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 4)
        txt = pytesseract.image_to_string(thr, config="digits")
        #txt  = re.findall('(\d{9})\D', txt)[0]

    return txt
'''
    
# M5Pr5         191876320
# RWgrP         202131290
# 6pVH4         193832560
print(readNumber('M5Pr5.png'))
print(readNumber('RWgrP.png'))
print(readNumber('6pVH4.png'))

相关的问题是关于这一联系Read text below barcode pytesseract python


Tags: to函数字符串imageretxtimgstring
3条回答

当条件满足时,您可以简单地从函数返回:

# Suppose the string is stored in text variable

if len(text) == 9:
    return

要退出函数,您的意思是从调用函数的位置返回吗

如果是,则使用

if len(stringVarible)==9:
   return

使用正则表达式。如果字符串包含9个相邻数字,则下面的正则表达式将匹配

\d{9,}

相关问题 更多 >