0

I am trying to iterate through my replace() function, to remove [1:n] in my .txt file (see image below), but it does not seem to work.

enter image description here

I have tried multiple things:

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)

also:

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)

But both without success.

Does anyone know how to solve this problem?

2
  • 1
    Yes, of course, so for instance the data contains the following sentence: "[113][114][115] Een paar dagen voor de inhuldiging protesteerde de lokale Turkse gemeenschap tegen de oprichting van het monument.[116]" and I expect the output to be: "Een paar dagen voor de inhuldiging protesteerde de lokale Turkse gemeenschap tegen de oprichting van het monument." @ohthatgeoff if that answers your question. Commented Dec 31, 2020 at 21:25
  • 1
    line.replace does not modify line, it modifies z. Also, f.close is not needed with the with context manager. Commented Dec 31, 2020 at 21:27

1 Answer 1

2

This solution uses the re.sub() function to replace those characters.

import re

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

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

print(output)

Output

OK this is some text.
just some more text.

Update:

Adding a file reading example. Make sure to pass the file as the first argument to the script.

import re
import sys

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

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

print(output)
Sign up to request clarification or add additional context in comments.

2 Comments

I tried doing it like this: import re with open('glad.txt', 'rt') as f: content = f.read() output = re.sub(r'[\d+]', '', content) print(output) but this game me a blank output
Updated the answer to have a file reading example, hopefully that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.