我有形式替換字符串,它的周圍是已知的,但該字符串的值是不知道的Python
**var beforeDate = new Date('2015-08-21')**
這裏的字符串我不知道paranthesis之間的值()。我想用其他日期替換這個日期。我如何用Python做到這一點? 我想打開文件,然後使用語言的標準替換函數,但由於beween()的值不知道,所以不可能。
這段代碼會有很多代碼,並且在這段代碼之後,因此用新行替換整行將不起作用,因爲它會覆蓋圍繞此代碼段的代碼。
我有形式替換字符串,它的周圍是已知的,但該字符串的值是不知道的Python
**var beforeDate = new Date('2015-08-21')**
這裏的字符串我不知道paranthesis之間的值()。我想用其他日期替換這個日期。我如何用Python做到這一點? 我想打開文件,然後使用語言的標準替換函數,但由於beween()的值不知道,所以不可能。
這段代碼會有很多代碼,並且在這段代碼之後,因此用新行替換整行將不起作用,因爲它會覆蓋圍繞此代碼段的代碼。
如何使用正則表達式?運行後
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"
爲什麼你用open(「output.txt」,「w」)將outline縮進爲outfile :,它不會和前一個縮進級別一樣? –
好眼睛。第二個「with」確實不需要在第一個內部縮進。編輯。 – Kevin
「雖然它在您提供的示例代碼上運行良好,但在我的代碼中它卻不起作用。\ n var afterDate = new Date('2015-08-19')已被轉換爲\ n P15- 08-13); –
就個人而言,我經常發現re.split()來比re.sub()更簡單。該重用凱文的代碼,並且將捕獲的一切,它(加上中間組),然後更換中間組:
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,這個特殊問題可能足夠小,不需要重錘。這裏是相同的代碼沒有重新:
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)
你的方法非常巧妙::)爲+1 –
這是什麼東西只出現一次在文件中,或有幾次發生?同一日期是否在多個地方使用? –
一旦它將在變量beforeDate = new Date('date_I_want_to_Put')中初始化,然後一旦它的值將用於比較的特定位置,如果some_date> beforeDate .... –
您是否已經考慮/解僱了使用常規表達式(重新模塊)找到要替換的字符串? – James