替换环境已知但字符串值未知的字符串

2024-10-01 02:37:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串的形式

**var beforeDate = new Date('2015-08-21')**

这里我不知道paranethesis()之间的值。我想用其他日期代替这个日期。我怎样才能用Python来做呢? 我想打开文件,然后使用该语言的标准replace函数,但是由于beween()的值未知,所以这是不可能的。你知道吗

这个代码段以及这个代码段之后会有很多代码,所以用新行替换整行代码是行不通的,因为它会覆盖这个代码段周围的代码。你知道吗


Tags: 文件函数字符串代码语言new标准date
2条回答

就我个人而言,我通常重新拆分()使用起来比回复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))

你可以放弃捕获中间组,但你会在列表中插入内容。换个地方比较容易。你知道吗

奥托,这个问题可能很小,不需要重锤。以下是相同的代码,没有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)

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

你知道吗温度.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"

你知道吗主.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)

你知道吗输出.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"

相关问题 更多 >