【问题标题】:python, string.replace() and \npython, string.replace() 和 \n
【发布时间】: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查看。它对我有用,您确定给定参数没有问题吗?

标签: python string replace


【解决方案1】:

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

你必须这样做:

bookstring = bookstring.replace(pgdel, htmlpg)

你也忘了调用函数close()。看看你有多少textin.close?你必须用括号来调用它,比如 open:

textin.close()

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

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

  • 运行脚本时,别忘了把.txt结尾:

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

我希望这些帮助!

【讨论】:

  • 这是一个需要修复的关键错误,但仍然同样的问题仍然存在。将编辑我的问题以包含此编辑。谢谢!
  • 调用了封闭的函数,并编辑了我的问题以反映同样的问题。它仍然无法正常工作。
  • @user1893148 我添加了更多信息
  • 感谢您的帮助。疯了,没人能复制。
【解决方案2】:

这是一种完全不同的方法,它使用 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

由于没有人知道发生了什么,所以值得一试。

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2015-08-05
    • 2021-07-16
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多