【问题标题】:Removing page numbers from a .txt file in Python在 Python 中从 .txt 文件中删除页码
【发布时间】:2015-04-08 08:05:00
【问题描述】:

我正在尝试加载电子书的 .txt 文件并删除包含页码的行。这本书看起来像:

2
Words
More words.

More words.

3
More words.

这是我目前所拥有的:

x = 1

with open("first.txt","r") as input:
    with open("last.txt","wb") as output: 
        for line in input:
            if line != str(x) + "\n":
                output.write(line + "\n")
                x + x + 1

我的输出文件删除了所有空白(新行)(我不想要),它甚至没有删除数字。有没有人有任何想法?谢谢!

【问题讨论】:

  • 您希望x + x + 1 做什么?
  • 哎呀,我的意思是:x = x + 1。不过,纠正这个问题并没有解决任何一个问题(空白或不删除任何数字)。我这样做是因为一旦找到页码(例如第 1 页),我希望它查找下一个(例如第 2 页)。如果出于某种原因这本书有一整行只有一个不是页码但确实是书的一部分的数字,这也将有所帮助。
  • 您也可以使用x += 1。但是,如果按照示例,它不是从第 1 页开始呢?
  • 完全合理,我只是想我会手动编辑它。

标签: python string file file-io text-files


【解决方案1】:

1) 您不必打开二进制文件open("last.txt","wb") -> open("last.txt","w") 2) x + x + 1 -> x += 1

但是,你可以做得更简单

with open("first.txt","r") as input:
    with open("last.txt","w") as output: 
        for line in input:
            line = line.strip() # clear white space
            try: 
                int(line) #is this a number ?
            except ValueError:
                output.write(line + "\n")

【讨论】:

  • 您不必添加strip 并附加\nint('2\r\n') 的计算结果为2。此外,绝对不能出现在代码中的 except 子句。 Errors should never pass silently. Unless explicitly silenced。您应该明确说明 - int() 方法会引发 ValueError
  • 可以是 \s2\s 而不是 \r\n。 int(line) 还能抛出什么其他异常(我们关心的)?
  • 我不确定\s 是什么意思。 int() 可以处理string.whitespace 中列出的任意数量的前导和尾随字符。关于异常 - ìnt() 也可以抛出 TypeError,但绝不在这种情况下(行始终是字符串)。口译员也可以提出KeyboardInterrupt,您会保持沉默。而你永远不想这样做。
  • \s 在空格中。注意到,我不知道空格的处理。关于例外,在这个特定的例子中,它是非常无害的(我们试图展示一种方法)。不过,我会编辑它。
  • 这对我的文件很有效。非常感谢大家!
【解决方案2】:

改进的解决方案 - 减少一个缩进级别,避免不必要的strip 和字符串求和,捕获显式异常。

with open("first.txt","r") as input_file, open("last.txt","w") as output_file:
    for line in input_file:
        try: 
            int(line)
        except ValueError:
            output_file.write(line)

【讨论】:

    【解决方案3】:

    检查是否可以将该行转换为整数,如果成功则跳过该行。不是最快的解决方案,但应该可以。

    try:
       int(line)
       # skip storing that line
       continue
    except ValueError:
       # save the line to output
    

    【讨论】:

    • 太晚了,Tasos 的回答就是这样。
    【解决方案4】:

    使用正则表达式忽略仅包含数字的行。

    import sys
    import re
    
    pattern = re.compile("""^\d+$""")
    
    for line in sys.stdin:
        if not pattern.match(line):
            sys.stdout.write(line)
    

    【讨论】:

    • 你应该使该字符串原始,而不是多行:r"^\d+$"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多