【问题标题】:Replace instances of a pattern in a file替换文件中模式的实例
【发布时间】:2020-11-02 18:54:20
【问题描述】:

我正在尝试打开一个文件,使用re 找到一个模式,然后将模式的每个实例传递给一个函数进行处理,然后替换文件中的每个模式实例。我有一个工作函数。

from datetime import datetime
from time import time

def replacetimestamp(replace):
    #document uses milliseconds not seconds.
    x = replace * .001
    dt_object = datetime.fromtimestamp(x)
    return dt_object
    print(dt_object)

一切都很好,所以当我尝试在我的主脚本中使用该函数时,我遇到了问题。我想要么我破坏了re 对象,要么我没有写入文件,但我尝试的一切都不起作用。

这是其余的:

import re
import time, datetime
import replacetimestamp
timestamp = re.compile(r'/d{13}')
for  line in open("testpython.json"):
    for timestamp in re.finditer(timestamp, line):
        timestamp.replacetimestamp()

【问题讨论】:

  • python 3.9版

标签: json python-3.x string python-re


【解决方案1】:

为此使用re.sub。它可以使用基于匹配的替换替换所有非重叠匹配的函数。示例:

import re
from datetime import datetime

test_data = 'stamp 1604344808485 stamp 1604344809000'

# re.sub passes a match object (m) into this function.
# m.group(0) is the string that matched.
def replace_timestamp(m):
    stamp = int(m.group(0)) * .001
    # Replace with the string representation of the datetime object,
    # not the object itself.  Use datetime.strptime() if a different
    # format is needed.
    return str(datetime.fromtimestamp(stamp))

updated = re.sub(r'\d{13}',replace_timestamp,test_data)
print(updated)

输出:

stamp 2020-11-02 11:20:08.485000 stamp 2020-11-02 11:20:09

对于您的情况,以下内容应该可以工作(未经测试):

with open('testpython.json') as infile, open('outpython.json','w') as outfile:
    for line in infile:
        line = re.sub(r'\d{13}',replace_timestamp,line)
        outfile.write(line)

【讨论】:

    猜你喜欢
    • 2010-12-26
    • 1970-01-01
    • 2012-01-25
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2013-06-26
    相关资源
    最近更新 更多