gpt4 book ai didi

python, string.replace() 和\n

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:27 29 4
gpt4 key购买 nike

(编辑:该脚本似乎对这里试图提供帮助的其他人有用。是因为我正在运行 python 2.7 吗?我真的很茫然...)

我有一个书的原始文本文件,我想用页面标记。

假设文本文件是:

some words on this line,
1
DOCUMENT TITLE some more words here too.
2
DOCUMENT TITLE and finally still more words.

我正在尝试使用 python 将示例文本修改为:

some words on this line,
</pg>
<pg n=2>some more words here too,
</pg>
<pg n=3>and finally still more words.

我的策略是将文本文件作为字符串加载。构建与数字列表对应的搜索字符串和替换字符串。替换字符串中的所有实例,并写入新文件。

这是我写的代码:

from sys import argv
script, input, output = argv

textin = open(input,'r')
bookstring = textin.read()
textin.close()

pages = []
x = 1
while x<400:
pages.append(x)
x = x + 1

pagedel = "DOCUMENT TITLE"

for i in pages:
pgdel = "%d\n%s" % (i, pagedel)
nplus = i + 1
htmlpg = "</p>\n<p n=%d>" % nplus
bookstring = bookstring.replace(pgdel, htmlpg)

textout = open(output, 'w')
textout.write(bookstring)
textout.close()

print "Updates to %s printed to %s" % (input, output)

脚本运行没有错误,但它也没有对输入文本进行任何更改。它只是一个字符一个字符地重印它。

我的错误与硬返回有关吗?\n?非常感谢任何帮助。

最佳答案

在 python 中,字符串是不可变的,因此 replace 返回替换后的输出,而不是就地替换字符串。

你必须做到:

bookstring = bookstring.replace(pgdel, htmlpg)

您还忘记调用函数 close()。看看你有 textin.close 吗?你必须用括号调用它,比如 open:

textin.close()

您的代码适合我,但我可能会添加更多提示:

  • Input 是一个内置函数,所以或许可以尝试重命名它。虽然它可以正常工作,但它可能不适合您。

  • 运行脚本时,不要忘记把.txt结尾:

    • $ python myscript.py file1.txt file2.txt
  • 确保在测试脚本时清除 file2 的内容

希望这些对您有所帮助!

关于python, string.replace() 和\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17461107/

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