python - 使用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 文件中的括号注释?
解决方案
正则表达式的问题是您无法处理嵌套括号。像“(())”这样的东西肯定会失败。
所以假设每个'('后面跟着一个')',如果你能这样处理它会更好:
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 .
推荐阅读
- c# - c#:从标准 gac 程序集的使用行获取程序集
- gradle - 如何在 Spock 测试中从 Gradle 的 ext 块访问方法?
- sql - 是否可以加入日期列和字符串列?
- python - Python为子进程创建超时
- typescript - Typescript 类型别名空数组括号
- node.js - 由于 MERN 堆栈应用程序中客户端和后端之间的连接问题,未提供静态文件
- python - 消除 json/dictionary 中的所有空结构
- angular - Angular 2+ 自定义表单验证打破了表单方法
- javascript - 在不同屏幕尺寸上放大的 HTML Jumbotron 图像
- c++ - 非恒定操作的 DFS 时间复杂度