从python的字符串中删除多余的\ n

问题描述 投票:0回答:1

我最近一直在学习python中的文本识别。将图像转换为字符串时,它会在我的图像中随机输出一个额外的换行符。我尝试将其删除,但似乎找不到方法。我的目标是将选择项分成相应的字符串

这是我的代码和图像ROI_0.png

choices = cv2.imread("ROI_0.png", 0)
custom_config = r'--oem 3 --psm 6'
c = pytesseract.image_to_string(choices, config=custom_config, lang='eng')

print(c.rstrip("\n")) #my attempt
text = repr(c)
print(text)
newtext = text.split("\\n")
print(newtext)

输出

a. E. 0. 125

b. R. A. 3846
c. R. A. 3396
d. R. A. 7925


'a. E. 0. 125\n\nb. R. A. 3846\nc. R. A. 3396\nd. R. A. 7925'

["'a. E. 0. 125", '', 'b. R. A. 3846', 'c. R. A. 3396', "d. R. A. 7925'"]
python-3.x opencv python-tesseract
1个回答
0
投票

您可以做的是将多行换成一个新行:

import re

x = re.sub(r'\n{2, 10}', '\n', c)   # \n is new line, {2,10} is the range of occurrences of the newline that I'm searching for.

所以会是这样:

choices = cv2.imread("ROI_0.png", 0)
custom_config = r'--oem 3 --psm 6'
c = pytesseract.image_to_string(choices, config=custom_config, lang='eng')

x = re.sub(r'\n{2, 10}', '\n', c)

print(x.rstrip("\n"))
© www.soinside.com 2019 - 2024. All rights reserved.