【问题标题】:How to replace old text with new one between some specific lines in python?如何在python中的某些特定行之间用新文本替换旧文本?
【发布时间】:2022-01-14 08:46:47
【问题描述】:

就像,我有一个类似 .txt 的文件

Hello, this Stackoverflow
<! replace starts from here !>
Currently time is 7:27 pm.
<! replace ends here !>

Have a nice day.

<! replace starts from here !>
Thanks Devs...
<! replace ends here !>

我希望上面的 .txt 文件为:-

Hello, this Stackoverflow
<! replace starts from here !>
Stackoverflow helps us very much.
<! replace ends here !>

Have a nice day.

<! replace starts from here !>
Thanks Developers.....
<! replace ends here !>

但我不能使用下面的代码,因为&lt;! replace starts here !&gt;&lt;! replace ends here !&gt; 之间的行可以是任何随机文本。

text = open("file.txt").read()
new_text = text.replace("Currently time is 7:27 pm.", "Stackoverflow helps us very much.") #like this for each

希望,我能让你明白我想说的话。 ????

请以任何方式指导我。

【问题讨论】:

  • 您是否尝试过按句子而不是按“”或“”等字符分割文件,而是按 txt 文件的内容?在此之后,如果您发现了一个,您可以简单地在随后的拆分组件上处理您想要的内容,直到找到结束替换过程的段。如果您可以接受,我可能会撰写回复并获得奖励。
  • 先生,请举例说明一下,以便更好地理解......

标签: python python-3.x replace


【解决方案1】:
  1. 将文本拆分为行列表。
  2. 找到第一个替换标记;存储它的索引。
  3. 找到第二个替换标记;存储它的索引。
  4. 删除列表中第一个和第二个索引之间的条目。
  5. 从第一个索引开始插入新行。
  6. 加入并输出修改后的行。

【讨论】:

  • 您能否举个例子来解释一下,以便更好地理解......
猜你喜欢
  • 1970-01-01
  • 2014-08-15
  • 2019-01-19
  • 2022-01-19
  • 1970-01-01
  • 2023-01-30
  • 2017-11-03
  • 1970-01-01
  • 2013-12-13
相关资源
最近更新 更多