Python,字符串。替换()和\n

2024-06-23 19:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

(编辑:这个剧本似乎对其他想帮忙的人有用。是因为我运行的是python2.7吗?我真的不知所措……)

我有一本书的原始文本文件,我试图用页面来标记。在

假设文本文件是:

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

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

^{pr2}$

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

下面是我写的代码:

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?非常感谢任何帮助。在


Tags: 字符串文本inputoutputtitlemoresomepages
2条回答

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

你必须做到:

bookstring = bookstring.replace(pgdel, htmlpg)

您还忘记了调用函数close()。看看你是怎么得到textin.close?你必须用括号来调用它,比如open:

^{pr2}$

你的代码对我很有用,但我可以再补充一些提示:

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

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

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

我希望这些有帮助!在

这里有一个完全不同的方法,它使用re(导入re模块,这样就可以工作了):

doctitle = False
newstr = ''
page = 1

for line in bookstring.splitlines():
    res = re.match('^\\d+', line)
    if doctitle:
        newstr += '<pg n=' + str(page) + '>' + re.sub('^DOCUMENT TITLE ', '', line)
        doctitle = False
 elif res:
     doctitle = True
     page += 1
    newstr += '\n</pg>\n'
 else:
    newstr += line

print newstr

既然没人知道发生了什么,那就值得一试。在

相关问题 更多 >

    热门问题