替换其周围环境已知但字符串值不为Python的字符串

时间:2015-08-24 11:43:51

标签: python string python-2.7 file-io

我有一个表格

的字符串
**var beforeDate = new Date('2015-08-21')**

这里我不知道paranthesis()之间的值。我想将此日期替换为任何其他日期。我怎么能在Python中做到这一点? 我想打开文件,然后使用该语言的标准替换函数,但由于未知的值beween(),这是不可能的。

此代码段以及此代码段之后会有很多代码,因此用新行替换整行将无法正常工作,因为它会覆盖此代码段周围的代码。

2 个答案:

答案 0 :(得分:2)

使用正则表达式怎么样?例如:

TEMP.TXT

print "I've got a lovely bunch of coconuts"
var beforeDate = new Date('2015-08-21') #date determined by fair die roll
print "Here they are, standing in a row"

main.py

import re

new_value = "'1999-12-31'"
with open("temp.txt") as infile:
    data = infile.read()
    data = re.sub(r"(var beforeDate = new Date\().*?(\))", "\\1"+new_value+"\\2", data)
with open("output.txt", "w") as outfile:
    outfile.write(data)
运行后

output.txt:

print "I've got a lovely bunch of coconuts"
var beforeDate = new Date('1999-12-31') #date determined by fair die roll
print "Here they are, standing in a row"

答案 1 :(得分:2)

就个人而言,我通常认为re.split()比re.sub()更易于使用。这将重用Kevin的代码,并将捕获它所做的一切(加上中间组),然后替换中间组:

import re

new_value = "'1999-12-31'"
with open("temp.txt") as infile:
    data = infile.read()

data = re.split(r"(var beforeDate = new Date\()(.*?)(\))", data)
# data[0] is everything before the first capture
# data[1] is the first capture
# data[2] is the second capture -- the one we want to replace
data[2] = new_value

with open("output.txt", "w") as outfile:
    outfile.write(''.join(stuff))

您可以放弃捕获中间组,但随后您将在列表中插入内容。只做替换更容易。

OTOH,这个特殊的问题可能足够小,不需要锤子。这是相同的代码,没有re:

new_value = "'1999-12-31'"
with open("temp.txt") as infile:
    data = infile.read()

data = list(data.partition('var beforeDate = new Date('))
data += data.pop().partition(')')
data[2] = new_value

with open("output.txt", "w") as outfile:
    for stuff in data:
        outfile.write(stuff)