在python中搜索并替换多个字符串

时间:2017-05-15 09:41:03

标签: python python-3.x

这是我的代码 我想搜索并替换三个字符串

tmp="/tmp"
day = datetime.date.today().day
today = datetime.date.today()
year =datetime.date.today().year
month = today.strftime('%b')

f1 = open("%s/backup.txt" % (tmp), 'r')
f2 = open("%s/backup1.txt" % (tmp), 'w')
for line in f1:
      f2.write(line.replace('day',  "%s" % (day)))
f1.close()
f2.close()

f1 = open("%s/backup1.txt" % (tmp), 'r')
f2 = open("%s/backup2.txt" % (tmp), 'w')
for line in f1:
      f2.write(line.replace('mon',  "%s" % (mon)))
f1.close()
f2.close()

f1 = open("%s/backup2.txt" % (tmp), 'r')
f2 = open("%s/backup3.txt" % (tmp), 'w')
for line in f1:
      f2.write(line.replace('year',  "%s" % (year)))
f1.close()
f2.close()

无论如何只需一次拍摄并减少LOC?

我想一次性搜索和替换年,星期一和日 的问候,

2 个答案:

答案 0 :(得分:2)

你可以在同一个循环中执行三个替换,之前将行写入新文件。

f1 = open("%s/backup.txt" % (tmp), 'r')
f2 = open("%s/backup1.txt" % (tmp), 'w')
for line in f1:
    new_line = line.replace('day',  "%s" % (day))
    new_line = line.replace('mon',  "%s" % (mon))
    new_line = line.replace('year',  "%s" % (year))
    f2.write(new_line)
f1.close()
f2.close()

如果你愿意的话,你甚至可以在同一条线上做所有三个,尽管这条线很长并且应该用\打破。此外,您可以(并且应该)使用with来打开和关闭文件。

with open("%s/backup.txt"  % tmp, 'r') as f1, \
     open("%s/backup1.txt" % tmp, 'w') as f2:
    for line in f1:
        new_line = line.replace('day',  "%s" % day) \
                       .replace('mon',  "%s" % mon) \
                       .replace('year', "%s" % year)
        f2.write(new_line)

根据@bruno的想法,您还可以创建一个包含替换的词典,然后使用regular expression来查找" day"或者" mon"或者"年" "day|mon|year"并将其替换为dict中的值。

>>> day, mon, year = 2017, 5, 15
>>> repl = {"day": day, "mon": mon, "year": year}
>>> line = "test string with day, mon, and year in it"
>>> re.sub("day|mon|year", lambda m: str(repl.get(m.group())), line)
'test string with 2017, 5, and 15 in it'

更好:如果你可以控制模板文件,你可以将要替换的部分包装到{...}中,然后使用str.format进行替换(假设{...}做没有出现在文件中。)

>>> line = "test string with {day}, {mon}, and {year} in it"
>>> line.format(**repl)
'test string with 2017, 5, and 15 in it'

答案 1 :(得分:2)

tmp="/tmp"
today = datetime.date.today()
day = "%s" % today.day
year = "%s" % today.year
month = today.strftime('%b')

replacements = [
    # find -> replace
    ('day', day),
    ('mon', mon),
    ('year', year)
    ]


with open("%s/backup.txt" % (tmp), 'r') as source, \
   open("%s/backup1.txt" % (tmp), 'w') as dest:

    for line in source:
        for target, replacement in replacements:
            line = line.replace(target, replacement) 
      dest.write(line)