2011-08-05 11 views
6

में पाइथन रेगेक्स findall मुझे एक इनपुटफाइल मिला जिसमें जावास्क्रिप्ट कोड है जिसमें कई पांच-आंकड़े आईडी हैं। मैं की तरह एक सूची में ये आईडी करना चाहते हैं:आउटपुट फ़ाइल

53231,53891,72829 आदि

यह मेरा वास्तविक अजगर फ़ाइल है:

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

मैं कैसे इन आईडी में प्राप्त कर सकते हैं आउटपुट फाइल की तरह मैं इसे चाहता हूँ? इस सवाल का जवाब है, तो समस्या का हल

धन्यवाद

उत्तर

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

धन्यवाद एक बहुत – Florian

+0

@Florian काम किया, जवाब को स्वीकार (वोट नीचे 'V' निशान गिनती) पर विचार करें। – MatToufoutu

संबंधित मुद्दे