Python 正则表达式 findall 输出到文件
我有一个输入文件,里面包含了一段JavaScript代码,这段代码里有很多五位数的ID。我想把这些ID整理成一个列表,像这样:
53231, 53891, 72829等等
这是我现在的Python文件:
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")
我该怎么做才能把这些ID按照我想要的格式放到输出文件里呢?
谢谢
1 个回答
12
这段内容是关于编程问题的讨论,主要涉及一些技术细节和解决方案。虽然具体的问题没有被直接回答,但大家分享了各自的看法和经验,帮助理解这个问题的不同方面。
在编程中,遇到问题是很常见的,很多时候我们需要通过查阅资料或者向他人请教来找到解决办法。这个讨论的目的就是为了让大家更好地理解问题,并找到合适的解决方案。
如果你对某个特定的编程问题感到困惑,不妨多看看类似的讨论,或者尝试自己动手解决,实践是最好的老师。
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)