【问题标题】:Replacing a string whose surroundings are known but the value of the string is not known Python替换周围已知但字符串值未知的字符串 Python
【发布时间】:2015-08-24 11:43:50
【问题描述】:

我有一个表单字符串

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

这里我不知道括号()之间的值。我想用任何其他日期替换这个日期。我怎样才能在 Python 中做到这一点? 我想打开文件,然后使用语言的标准替换功能,但是由于不知道 beween () 的值,所以这是不可能的。

在这个 sn-p 以及在这个 sn-p 之后会有很多代码,所以用新行替换整行是行不通的,因为它会覆盖这个 sn-p 周围的代码。

【问题讨论】:

  • 这是在文件中只出现一次的东西,还是多次出现?同一日期是否在多个地方使用?
  • 一旦在变量 beforeDate = new Date('date_I_want_to_Put') 中初始化,然后在特定位置使用它的值进行比较,如果 some_date > beforeDate ....跨度>
  • 您是否考虑过/驳回使用正则表达式(re 模块)来查找要替换的字符串?
  • “我不知道括号()之间的值”。即使您不知道值本身,您是否对值的结构有所了解?例如,它是否总是用单引号括起来的字符串文字?
  • @James:是的,正则表达式对我来说似乎也是最好的选择,虽然不知道如何使用它们

标签: python string python-2.7 file-io


【解决方案1】:

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

临时文件

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") as outfile: 的行,它不会和之前的缩进级别一样吗?
  • 好眼光。第二个with 确实不需要在第一个内缩进。已编辑。
  • " 虽然它在您提供的示例代码上运行良好,但在我的代码上它不起作用。一行是 \n var afterDate = new Date('2015-08-19'); 有已转换为\n P15-08-13);
  • 尝试更改您的代码 new_value = "1999-12-31",我刚刚删除了 new_value 中的单引号。
  • 有趣...您能否在pastebin 上放一个示例文档,以便我可以在自己的机器上复制问题?
【解决方案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)

【讨论】:

  • 你的方法很巧妙:) +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2021-10-29
相关资源
最近更新 更多