你好,我是Python的初学者,刚刚开始学习Python并使用RegEx进行文本操作。 如果我违反了StackOverflow的一些规则,我会提前道歉
我正在用Python编写一个脚本,从第一行开始(剪切)日期和时间,并在每一行上替换“date”“TimeWindowStart”和“TimeWindowEnd”
ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
我知道如何选择与正则表达式日期
([0-9][0-9]|2[0-9])/[0-9][0-9](/[0-9][0-9][0-9][0-9])?
如何选择时间
([0-9][0-9]|2[0-9]):[0-9][0-9](:[0-9][0-9])?
但是我一直在思考如何选择文本的一部分,复制它,然后找到我想用替换的文本回复sub功能
所以最终输出如下所示:
ReportDate=, TimeWindowStart=, TimeWindowEnd=
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
这是我的密码:
输出:
这是一个部分的答案,因为我不知道pythonapi操作文本文件特别好。您可以读取文件的第一行,并提取报告日期和开始/结束窗口时间的值。你知道吗
写出第一行,去掉三个变量的值。你知道吗
然后,您只需读入后面的每一行,并进行以下替换:
以这种方式处理每一行之后,可以将其写入输出文件。你知道吗
首先,您可以在regex查询中指定一个量词,因此如果您想要4个数字,您不需要
[0-9][0-9][0-9][0-9]
,但可以使用[0-9]{4}
。要捕获表达式,请将其包装在圆括号中value=([0-9]{4})
将只提供数字如果你想使用
re.sub
,你只需要给它一个模式,一个替换字符串和你的输入字符串,例如re.sub(pattern, replacement, string)
因此:
输出:
相关问题 更多 >
编程相关推荐