【问题标题】:how to iterate through replace() function python如何遍历replace()函数python
【发布时间】:2020-12-31 21:19:42
【问题描述】:

我正在尝试遍历我的 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)

还有:

with open('glad.txt', 'rt') as f:
  content = f.read()
  test = open("out.txt", "wt")
  for line in content:
    for x in range(120):
      z = test.write(line.replace(f"[{x}]", ""))
  f.close()
print(z)

但都没有成功。

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

【问题讨论】:

  • 是的,当然,例如数据包含以下句子:“[113][114][115] Een paar dagen voor de inhuldiging Prototeerde de lokale Turkse gemeenschap tegen de oprichting van het Monument .[116]”,我希望输出是:“Een paar dagen voor de inhuldiging Prototeerde de lokale Turkse gemeenschap tegen de oprichting van het Monument。” @ohthatgeoff 如果这回答了你的问题。
  • line.replace 不修改行,它修改了 z。此外,with 上下文管理器不需要 f.close。

标签: python text str-replace


【解决方案1】:

此解决方案使用re.sub() 函数来替换这些字符。

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 with open('glad.txt', 'rt') as f: content = f.read() output = re.sub(r'[\ d+]', '', content) print(output) 但是这个游戏我是空白输出
  • 更新了答案以提供文件读取示例,希望对您有所帮助。
猜你喜欢
  • 2018-12-25
  • 2014-05-13
  • 2022-06-13
  • 1970-01-01
  • 2018-08-16
  • 2021-12-23
  • 1970-01-01
  • 2020-09-23
  • 2022-01-24
相关资源
最近更新 更多