【问题标题】:Removing extra \n from a string in python从python中的字符串中删除额外的\ n
【发布时间】:2020-05-26 02:30:58
【问题描述】:

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

这是我的代码和图片:

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】:

    您可以做的是将多个新行删除到一个新行:

    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"))
    

    【讨论】:

    • 非常感谢对我有用的是 x = re.sub(r'\n{2}', '\n', c)
    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多