首页 > 解决方案 > 使用python替换/删除文本文件中的附加注释

问题描述

我正在尝试删除文本文件中的所有括号注释。这是一个名为“sample.txt”的非常简短的示例:

第一句(评论 1)。第二句(第二条评论)。

我希望它看起来像这样:

第一句。第二句。

我已经尝试过以下形式的 re.sub ,但只能让它适用于字符串,而不适用于文本文件。这是我尝试过的许多事情之一:

intext = 'C:\\Users\\Sarah\\PycharmProjects\\pythonProject1\\sample.txt'
outtext = 'C:\\Users\\Sarah\\PycharmProjects\\pythonProject1\\EDITEDsample.txt'
with open(intext, 'r') as f, open(outtext, 'w') as fo:
    for line in f:
        fo.write(re.sub(r'\([^()]*\)', ''))

这不会给我一条错误消息,但它也不会对文本做任何事情。

with open (intext, 'r') as f, open(outtext, 'w') as fo:
    for line in f:
        fo.write(line.replace('(', " ").replace(')', " "))

这成功地删除了括号,但由于 .replace 不处理正则表达式,我不知道如何使用它来删除括号之间的任何文本。

我也试过

with open (intext, 'r') as f, open(outtext, 'w') as fo:
    for line in f:
        re.sub(r'\([^()]*\)', '', outtext)

但我收到一个错误,说我缺少一个字符串,这是预期的,因为 re.sub 需要字符串。我可以使用什么来删除/替换TEXT 文件中的括号注释?

标签: pythontext

解决方案


正则表达式的问题是您无法处理嵌套括号。像“(())”这样的东西肯定会失败。

所以假设每个'('后面跟着一个')',如果你能这样处理它会更好:

infile = ["Sentence one (comment 2). Second sentence (second comment).\n",
          "Sentence one (comment 2). Second sentence (second (comment)((((((())))))))."]

open_parenthese_counter = 0

for line in infile:
    for char in line:
        if open_parenthese_counter == 0:
            print(char, end='') # write into the output file.
        elif char == '(':
            open_parenthese_counter += 1
        elif char == ')':
            open_parenthese_counter -= 1  # = max(open_parenthese_counter-1, 0)        

然后根据您的需要进行更改。

输出:

Sentence one . Second sentence .
Sentence one . Second sentence .

推荐阅读