无法使用python re模块替换匹配的字符串

时间:2017-10-22 07:05:58

标签: python python-2.7 python-3.x

我的文件如下:

[sunday]
@office 
@home 
@store

[monday]
@office
@home
@store

现在我需要在@home之前添加时间,不仅仅是@home它可以是基于用户输入的三种中的任何一种。

[sunday]
@office
<2016-02-02>@home
@store

[monday]
@office
<2016-02-02>@home
@store
  

我的代码:

time= "2016-02-02"
group = "home"
with open("file.txt") as f:
    data = f.readlines()
    regex = r"^@"+re.escape(group)
    for line in data:
        result =  re.findall(regex,line)
        if result:
            timeline_added = "<"+time+">"+"@"+group
            re.sub(regex, timeline_added, data)

我正在

TypeError:expected string or buffer. I am using python 2.7

2 个答案:

答案 0 :(得分:1)

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

根据你的要求(在评论中)得到的最好的是使用itertools.groupby(请注意文档),然后转换为dict,以day作为键并使用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 day : monday
Enter the input : store
[sunday]
@office 
@home 
@store

[monday]
@office
@home
2016-02-02@store

答案 1 :(得分:0)

time= "2016-02-02"
group = "home"
with open("file.txt") as f:
    data = f.readlines()
    regex = r"^@"+re.escape(group)
    for line in data:
        result =  re.findall(regex,line)
        if result:
            timeline_added = "<"+time+">"+"@"+group
            re.sub(regex, timeline_added, line)

根据ZdaR评论,将数据更改为行并且工作正常,谢谢