reemplazar texto en un archivo con Python


Soy nuevo en Python. Quiero poder abrir un archivo y reemplazar cada instancia de ciertas palabras con un reemplazo dado a través de Python. como ejemplo, digamos reemplazar cada palabra 'cero' con '0', 'temp' con 'bob', y decir 'basura'con ' nada'.

Primero había empezado a usar esto:

for line in fileinput.input(fin):
        fout.write(line.replace('zero', '0'))
        fout.write(line.replace('temp','bob'))
        fout.write(line.replace('garbage','nothing'))

Pero no creo que esta sea una manera ni remotamente correcta de hacer esto. Luego pensé en hacer declaraciones if para verificar si la línea contiene estos elementos y si lo hace, luego reemplace cuál una que contiene la línea, pero por lo que sé de Python esta tampoco es realmente una solución ideal. Me encantaría saber cuál es la mejor manera de hacer esto. Gracias por adelantado!

Author: shadonar, 2012-10-26

7 answers

Esto debería hacerlo

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        outfile.write(line)

EDIT: Para abordar el comentario de Eildosa , si quieres hacer esto sin escribir en otro archivo, entonces terminarás teniendo que leer todo tu archivo fuente en memoria:

lines = []
with open('path/to/input/file') as infile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        lines.append(line)
with open('path/to/input/file', 'w') as outfile:
    for line in lines:
        outfile.write(line)

Editar: Si está utilizando Python 3.x, use replacements.items() en lugar de replacements.iteritems()

 68
Author: inspectorG4dget,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 07:26:40

Podría considerar usar un dict y re.sub para algo como esto:

import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
    return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
    for line in fin:
        fout.write(regex.sub(replfunc,line))

Esto tiene una ligera ventaja para replace en que es un poco más robusto para coincidencias superpuestas.

 7
Author: mgilson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-24 09:38:38

Si su archivo es corto (o incluso no extremadamente largo), puede usar el siguiente fragmento de código para reemplazar el texto en su lugar:

# Replace variables in file
with open('path/to/in-out-file', 'r+') as f:
    content = f.read()
    f.seek(0)
    f.truncate()
    f.write(content.replace('replace this', 'with this'))
 6
Author: John Calcote,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-21 23:20:57

El camino esencial es

  • read(),
  • data = data.replace() tan a menudo como lo necesite y luego
  • write().

Si lee y escribe todos los datos a la vez o en partes más pequeñas depende de usted. Debe hacer que dependa del tamaño esperado del archivo.

read() se puede reemplazar con la iteración sobre el objeto file.

 4
Author: glglgl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-10 07:26:00

Sería una forma más rápida de escribir...

in = open('path/to/input/file').read()
out = open('path/to/input/file', 'w')
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for i in replacements.keys():
    in = in.replace(i, replacements[i])
out.write(in)
out.close

Esto eliminó muchas de las iteraciones que sugieren las otras respuestas, y acelerará el proceso para archivos más largos.

 2
Author: Matt Olan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-26 15:08:12

Leyendo desde la entrada estándar, escriba 'code.py" según se indica:

import sys

rep = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

for line in sys.stdin:
    for k, v in rep.iteritems():
        line = line.replace(k, v)
    print line

Luego, ejecute el script con redirección o canalización (http://en.wikipedia.org/wiki/Redirection_ (informática))

python code.py < infile > outfile
 0
Author: satomacoto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-26 16:09:28

Este es un ejemplo corto y simple que acabo de usar:

Si:

fp = open("file.txt", "w")

Entonces:

fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"

No:

line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing
 0
Author: AmazingDayToday,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-05 02:16:38