无法使用python re模块替换匹配的字符串
我的文件如下所示:无法使用python re模块替换匹配的字符串,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我的文件如下所示: 现在我需要像这样在@home之前添加时间,而不仅仅是@home,根据用户输入,它可以是三者中的任何一个 [sunday] @office <2016-02-02>@home @store [monday] @office <2016-02-02>@home @store time=“2016-02-02” group=“home” 将open(“file.txt”)作为f: 数据=f.读线() regex=r“^@”+re.escape(组) 对
现在我需要像这样在@home之前添加时间,而不仅仅是@home,根据用户输入,它可以是三者中的任何一个
[sunday]
@office
<2016-02-02>@home
@store
[monday]
@office
<2016-02-02>@home
@store
time=“2016-02-02”
group=“home”
将open(“file.txt”)作为f:
数据=f.读线()
regex=r“^@”+re.escape(组)
对于行输入数据:
结果=re.findall(正则表达式,行)
如果结果为:
时间线_添加了=”“+“@”+组
re.sub(正则表达式,添加时间线,第行)
根据ZdaR的评论,将数据更改为line,并且工作正常,谢谢
time= "2016-02-02"
inp = input('Enter the input : ')
with open(r'file.txt','r') as f:
print ('\n'.join([time+i if i.strip()=='@'+inp else i for i in f.read().split('\n')]))
输出:
Enter the input : home
[sunday]
@office
2016-02-02@home
@store
[monday]
@office
2016-02-02@home
@store
Enter the day : monday
Enter the input : store
[sunday]
@office
@home
@store
[monday]
@office
@home
2016-02-02@store
根据您的要求(在评论中),我得到的最好结果是使用itertools.groupby(请注意doc),然后将日期转换为dict并使用dict项目
注意:这将假定您的一组日数据之间始终有一个空行
time= "2016-02-02"
from itertools import groupby
day = input('Enter the day : ')
inp = input('Enter the input : ')
with open(r'file.txt','r') as f:
grp = ([list(g) for k,g in groupby([i for i in f.read().split('\n')], lambda x:x=='') if not k])
dct = {i[0]:i[1:] for i in grp}
dct['['+day+']'] = [time+'@'+inp if inp in i else i for i in dct['['+day+']']]
for k,v in dct.items():
print (k + '\n' + '\n'.join(i for i in v) + '\n')
输出:
Enter the input : home
[sunday]
@office
2016-02-02@home
@store
[monday]
@office
2016-02-02@home
@store
Enter the day : monday
Enter the input : store
[sunday]
@office
@home
@store
[monday]
@office
@home
2016-02-02@store
不应该是变量
组
a字符串
group=“home”
类型错误:预期的字符串或缓冲区在哪一行?@SreenadhTC与时间相同,“file.txt”
,等等@ZdaR是的,这应该是问题所在!虽然,我认为OP想要一个时间字符串,可能来自于我编辑的问题伙计们的datetime
package,但我错过了引号,请原谅,只需在re.sub(regex,timeline\u added,data)
中用line
替换数据即可。
感谢Santhosh,我只是好奇,若要求我只根据天在home下添加日期,比如若他们为周日输入,然后只在周日下更改,而不是在周一下的@home
time= "2016-02-02"
from itertools import groupby
day = input('Enter the day : ')
inp = input('Enter the input : ')
with open(r'file.txt','r') as f:
grp = ([list(g) for k,g in groupby([i for i in f.read().split('\n')], lambda x:x=='') if not k])
dct = {i[0]:i[1:] for i in grp}
dct['['+day+']'] = [time+'@'+inp if inp in i else i for i in dct['['+day+']']]
for k,v in dct.items():
print (k + '\n' + '\n'.join(i for i in v) + '\n')
Enter the day : monday
Enter the input : store
[sunday]
@office
@home
@store
[monday]
@office
@home
2016-02-02@store