Python正则表达式findall输出到文件中

7

我有一个包含许多五位数字id的javascript代码输入文件。我想将这些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)

@Florian 如果这个答案解决了你的问题,请考虑接受这个答案(在投票计数下面的 V 标记)。 - mdeous

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接