2011-08-05 10 views
6

tengo un archivo de entrada que contiene un código de JavaScript que contiene muchos identificadores de cinco cifras. Quiero tener estos ID en una lista como:Python regex findall en el archivo de salida

53231,53891,72829 etc

Este es mi archivo pitón real:

import re 

fobj = open("input.txt", "r") 
text = fobj.read() 

output = re.findall(r'[0-9][0-9][0-9][0-9][0-9]' ,text) 

outp = open("output.txt", "w") 

¿Cómo puedo obtener estos ID en el archivo de salida como lo quiero?

, gracias

Respuesta

11
import re 
# Use "with" so the file will automatically be closed 
with open("input.txt", "r") as fobj: 
    text = fobj.read() 
# Use word boundary anchors (\b) so only five-digit numbers are matched. 
# Otherwise, 123456 would also be matched (and the match result would be 12345)! 
output = re.findall(r'\b\d{5}\b', text) 
# Join the matches together 
out_str = ",".join(output) 
# Write them to a file, again using "with" so the file will be closed. 
with open("output.txt", "w") as outp: 
    outp.write(out_str) 
+0

Muchas gracias trabajaron – Florian

+0

@Florian si la respuesta soluciona el problema, la posibilidad de aceptar la respuesta (la marca 'V' a continuación los votos cuentan). – MatToufoutu