gpt4 book ai didi

python - python中遇到指定单词时如何在txt中添加\n

转载 作者:行者123 更新时间:2023-12-01 08:20:22 24 4
gpt4 key购买 nike

我有一个 txt 文件 (A.txt),其信息如下:

 259 96 339 96 339 249 259 249 person 200 12 22 23 333 312 33 249 car

我想使用 python 将这个 A.txt 修改为类似的内容:

 259 96 339 96 339 249 259 249 person
200 12 22 23 333 312 33 249 car

enter image description here

这意味着我必须在“人”或“车”后面添加 ('\n')。

我在查找单词位置时遇到困难,而seek(n)只能查找字符的位置。当我运行以下代码时

 f.seek(0)
f.write('\n')

它总是在末尾添加新行,而不是在前面。

最佳答案

假设我们将文件的全部内容放在一个字符串中,我们可以使用简单的替换方法,如下面的代码所示。

a = "259 96 339 96 339 249 259 249 person 200 12 22 23 333 312 33 249 car 12"
a = a.replace("person ", "person\n").replace("car ","car\n")
print(a)

以上代码将显示:

259 96 339 96 339 249 259 249 place

200 12 22 23 333 312 33 249 car

12

关于python - python中遇到指定单词时如何在txt中添加\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54685244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com