【发布时间】:2013-07-04 02:46:18
【问题描述】:
(编辑:该脚本似乎对这里试图帮助的其他人有用。是因为我正在运行 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?非常感谢任何帮助。
【问题讨论】:
-
/已编辑以包括对 bookstring replace 命令的更正,但问题仍然存在。
-
hmm...如果我运行该脚本,它确实将更改写入输出文件。你到底想做什么?我的意思是,它对我有用。
-
另外,它应该是
textin.close(),否则你不会调用该函数。textout.close也一样。 -
谢谢,现在反映在问题中。它仍然不适合我。我在 Mac 上使用 .txt 文件作为输入和输出文件。我从我的问题中尝试了测试示例,它仍然只是简单地复制输入文本而不对输出进行编辑。
-
尝试添加
print bookstring查看。它对我有用,您确定给定参数没有问题吗?