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

标签 python regex

我得到了一个输入文件,其中包含一个包含许多五位数 ID 的 JavaScript 代码。我想将这些 ID 放在如下列表中:

53231,53891,72829 etc

这是我实际的 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?

谢谢

最佳答案

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)

关于Python 正则表达式 findall 到输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6956279/

相关文章:

Python:检索受 SQL DELETE 查询影响的行数

ruby - 使用 UTF-8 字符串将 Ruby 中的第一个字母大写,但有异常(exception)

regex - 如何检测 Perl 中的空行?

正则表达式检查是否以 .jpg、.png 或 .gif 结尾的有效 URL

java - 如何跟踪正则表达式中的灾难性回溯?

python - 在 Pandas 中合并数据帧并忽略重复索引(有选择地)

python - 如何在 Python 中合并来自 3 个不同列表的嵌套子列表的元素?

python - Django 按名称获取 url 正则表达式

java - 正则表达式可选,在 primefaces 中使用allowTypes

python - 杀死模拟对象 : A Python Story