如何使用Python re模块在单个文件中将\n替换为空字符串
大家好。
我正在用Python图像库开发一个图像压缩系统。基本的工作流程是:
- 用命令读取某个文件夹里的所有图片:find /opt/images -name *.jpg > /opt/rs/images.txt
- 读取这个文件,把结果存储到一个Python列表里
- 遍历这个列表,创建一个图像对象,并把它作为参数传递给压缩函数
- 然后,把压缩后的图像复制到一个特定的文件夹,这个文件夹的名字是根据图像的名字来决定的。
举个例子:
/opt/buzon/17_499999_1_00000000_00000999_1.jpg
这是图像的真实名字:
最终结果是:
17_499999.jpg
输出目录是:/opt/ftp
应该以这样的方式存储:
1- 第一部分 00000000 - 第二部分 00000999 - 第三部分 1- 这个标志用来决定我们是否需要压缩这张图像(1表示不压缩,0表示压缩)
所以,图像的最终路径是:
/opt/ftp/1/00000000/00000999/17_499999.jpg (原始副本)
/opt/ftp/1/00000000/00000999/17_499999_tumb.jpg
现在,问题来了。当我读取存储find命令结果的文件时,文件的每一行都有一个\n字符。
我该如何用正则表达式来替换这个呢?
完整的源代码是这样的。欢迎任何建议。
import Image, os ,sys, re, subprocess, shlex
import ConfigParser
from symbol import except_clause
CONFIG_FILE = "/opt/scripts/config.txt"
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
entry_dir = config.get('directories', 'entry_dir')
out_dir = config.get('directories', 'out_dir')
def resize(img, box, fit, out):
'''Downsample the image.
@param img: Un objeto de la clase Imagen
@param box: tuple(x, y) - El recuadro de la imagen resultante
@param fix: boolean - el corte de la imagen para llenar el rectangulo
@param out: objeto de tipo fichero - guarda la imagen hacia la salida estandar
'''
# prepara la imagen con un factor de 2, 4, 8 y el algoritmo mas rapido
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
# Aqui se calcula el rectangulo optimo para la imagen
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = y2/2-box[1]*wRatio/2
y2 = y2/2+box[1]*wRatio/2
else:
x1 = x2/2-box[0]*hRatio/2
x2 = x2/2+box[0]*hRatio/2
# Este metodo es para manipular rectangulos de una determinada imagen
# definido por 4 valores que representan las coordenadas: izquierda,
# arriba, derecha y abajo
img = img.crop((x1,y1,x2,y2))
# Le damos el nuevo tamanno a la imagen con el algoritmo de mejor calidad(ANTI-ALIAS)
img.thumbnail(box, Image.ANTIALIAS)
return img
def removeFiles(directory):
"""
Funcion para borrar las imagenes luego de ser procesadas
"""
for f in os.listdir(directory):
path = os.path.abspath(f)
if re.match("*.jpg", path):
try:
print "Erasing %s ..." % (path)
os.remove(path)
except os.error:
pass
def case_partition(img):
"""
@desc: Esta funcion es la que realmente guarda la imagen en la
particion 0
@param: imagen a guardar
@output_dir: Directorio a guardar las imagenes
"""
nombre_imagen = img
nombre_import = os.path.splitext(nombre_imagen)
temp = nombre_import[0]
nombre_real = temp.split('_')
if nombre_real[4] == 0:
ouput_file = nombre_real[0] + nombre_real[1] + ".jpg"
output_dir = out_dir + "/%d/%d/%d/" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file)
else:
print "Esta imagen sera comprimida"
img = resize(img, 200, 200, 200) ## FIXME Definir el tamano de la imagen
# Salvamos la imagen hacia un objeto de tipo file
# con la calidad en 75% en JPEG y el nombre definido por los especialistas
# Este nombre no esta definido......
# FIXME
output_file = nombre_real[0] + nombre_path[1] + "_.jpg"
output_dir = out_dir + "/%d/%d" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(out)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
if __name__ == "__main__":
find = "find %s -name *.jpg > /opt/scripts/images.txt" % entry_dir
args = shlex.split(find)
p = subprocess.Popen(args)
f = open('/opt/scripts/images.txt', "r")
images = []
for line in f:
images.append(line)
f.close()
for i in images:
img = Image.open(filename) # Here is the error when I try to open a file
case_partition(img) # with the format '/opt/buzon/15_498_3_00000000_00000000_1.jpg\n'
# and the \n character is which I want to replace with nothing
removeFiles(entry_dir) #
#
祝好
3 个回答
有很多方法可以做到这一点,而不需要使用正则表达式。最简单且正确的方法是用 images.append(line.rstrip("\n"))
,你也可以用 images.append(line[:-1])
。
另外,你可以使用 glob() 模块来代替通过命令行调用 'find' 命令。这样可以直接得到一个 Python 列表的结果,而不需要处理文件。例如:images=glob.glob("*.jpg")
。你可以查看这个链接了解更多信息:http://docs.python.org/library/glob.html?highlight=glob
我想相关的代码行是这些:
for line in f:
images.append(line)
要去掉字符串中的 \n
,你可以直接在这个字符串上调用 strip()
方法:
for line in f:
images.append(line.strip())
假设s是一个包含换行符的字符串,你可以用s.strip("\n")来去掉字符串两端的换行符。这样做不需要用到复杂的正则表达式。