如何删除python中多个字符串之间的无效字符? [英] How to delete invalid characters between multiple strings in python?
问题描述
我正在使用西班牙语中的OCR进行项目.相机在一行文本中捕获不同的帧.文本行包含以下内容:
I'm working in a project with OCR in Spanish. The camera captures different frames in a line of text. The line of text contains this:
Este texto,无任何证据.
经过一些操作,我得到了这样的字符串:
After some operations I get strings like that:
s1 = "Este texto, es una p!"
s2 = "fste texto, es una |prueba u.-"
s3 = "jo, es una prueba del dispo‘"
s4 = "prueba del dispositivo \ec"
s5 = "del dispositivo lector par:"
s6 = "positivo lector para no xndev"
s7 = "lector para no videntes"
s8 = "¡r para no videntes."
我想加入字符串,以便可以将扫描行的文本存储在这样的最终字符串中:
I would like to join the string so that I can get the text of the scanned line in a final string like that:
sf = "Este texto, es una prueba del dispositivo lector para no videntes."
首先,我尝试在两个字符串之间使用SequenceMatcher
,但效果不佳:
To begin I tried to use SequenceMatcher
between two strings but it was not effective:
# -*- coding: utf-8 -*-
from difflib import SequenceMatcher as sq
s1 = "Este texto, es una p!"
s2 = "fste texto, es una prueba u.-"
match = sq(None, s1, s2).find_longest_match(0, len(s1), 0, len(s2))
print unicode(s1 + s2[match.b + match.size:])
结果包含无效字符,例如|
或!
:
The result has invalid characters like |
or !
:
>>>Este texto, es una p!|prueba u.-
在s2
和s3
之间:
>>>fste texto, es una |prueba u.-prueba del dispo‘
等等.我在Windows 7上使用的是python 2.7.
Etc. I'm using python 2.7 on Windows 7.
推荐答案
您应使用正则表达式 做类似的事情
You should use regex Do something like
import re
line = re.sub(r'\W', r'', line)
\ W表示任何无字字符.您可以在网站上了解有关正则表达式的更多信息: https://docs.python.org/2 /library/re.html
\W means any none word character. You may read more about regexes at site: https://docs.python.org/2/library/re.html
这篇关于如何删除python中多个字符串之间的无效字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!