回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我在python中有一个函数,它返回字符串(文本)的不同输出。我有不同的部分,我应该检查字符串,如果字符串是9位数字或包含9位数字,那么我需要在函数中执行,以在该点退出函数
我是python的新手,如果达到标准,我不知道如何在特定点退出函数。
比如说</p>
<pre><code>s = 'oodf 191876320x sd'
print(any(char.isdigit() for char in s))
</code></pre>
<p>这将检查字符串是否有数字。我需要添加另一个标准,以确保有相邻的9个数字。如果<code>True</code>,则在该点退出该函数</p>
<p>我正在处理的代码是从图像中读取数字(有三种不同的操作情况)
这是我的尝试,我欢迎任何想法</p>
<pre><code>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'))
</code></pre>
<p>相关的问题是关于这一联系<a href="https://stackoverflow.com/questions/66126756">Read text below barcode pytesseract python</a></p>