如何在python中迭代replace()函数

如何在python中迭代replace()函数,python,text,str-replace,Python,Text,Str Replace,我试图遍历replace()函数,删除.txt文件中的[1:n](见下图),但它似乎不起作用 我尝试了多种方法: with open('glad.txt', 'rt') as f: content = f.read() for line in content: for x in range(118): z = line.replace(f"[{x}]", "") f.close() print(z) 此外: 但两

我试图遍历replace()函数,删除.txt文件中的[1:n](见下图),但它似乎不起作用

我尝试了多种方法:

with open('glad.txt', 'rt') as f:
  content = f.read()
  for line in content:
    for x in range(118):
      z = line.replace(f"[{x}]", "")
  f.close()    
print(z)
此外:

但两者都没有成功

有人知道如何解决此问题吗?

此解决方案使用函数替换这些字符

import re

text = """
OK this is some text. [123][456][789]
just some more text.[007]
"""

output = re.sub(r'\[\d+\]', '', text)

print(output)
输出

OK this is some text.
just some more text.
更新:

添加一个文件读取示例。确保将文件作为第一个参数传递给脚本

import re
import sys

with open(sys.argv[1]) as fin:
    text = fin.read()

output = re.sub(r'\[\d+\]', '', text)

print(output)
此解决方案使用函数替换这些字符

import re

text = """
OK this is some text. [123][456][789]
just some more text.[007]
"""

output = re.sub(r'\[\d+\]', '', text)

print(output)
输出

OK this is some text.
just some more text.
更新:

添加一个文件读取示例。确保将文件作为第一个参数传递给脚本

import re
import sys

with open(sys.argv[1]) as fin:
    text = fin.read()

output = re.sub(r'\[\d+\]', '', text)

print(output)

是的,当然,因此,例如,数据包含以下句子:“[113][114][115]甚至paar dagen voor de inhuldiging抗议者de lokale Turkse gemeenschap tegen de oprichting van het纪念碑[116]”,我预计输出为:“即使是在瓦赫纪念碑附近的土耳其洛卡勒地区,也有人抗议。“@ohthatgeoff如果这回答了您的问题。line.replace不会修改line,它会修改z。此外,使用上下文管理器的
不需要f.close。是的,当然,因此,例如,数据包含以下句子:“[113][114][115]Een paar dagen voor de inhuldiging抗议者de lokale Turkse gemeenschap tegen de oprichting van het纪念碑[116]”,我预计输出为:“Een paar dagen voor de inhuldiging Respecteerde de lokale Turkse gemeenschap tegen de oprichting van het纪念碑。”@Ohthageoff如果这回答了你的问题。line.replace不修改line,它修改z。另外,f.close不需要使用上下文管理器
使用
。我尝试过这样做:使用open('glad.txt',rt'导入re)作为f:content=f.read()output=re.sub(r'[\d+],'',content)print(output),但是这个游戏我有一个空白的output更新了答案,有一个文件读取示例,希望能有所帮助。我试着这样做:用open('glad.txt','rt')导入re,作为f:content=f.read()output=re.sub(r'[\d+],'',content)print(output)但是这个游戏给我一个空白的输出更新了答案,有一个文件读取的例子,希望能有所帮助。