When using f.read() the iteration loops per letter

Viewed 243

I am iterating through my text file, but when I use the read() function, the loop iterates through the letters instead of the sentences.

with the following code:

for question in questions: # voor elke question moet er door alle lines geiterate worden
    print(f"Question: {question}")
    f = open("glad.txt", "r")
    text = f.read()
      # text = text.replace("\n", ". ")
      # text = text.replace(". .", "")
      # text = text.replace(".. ", ". ")
      # text = text.replace(".", ".\n")

      #text = text.strip(".. ")
      # test = text.replace('[bewerken | brontekst bewerken]', "")   
      # output = re.sub(r'\[\d+\]', '', test)
    for line in text:
      text = str(line) #het antwoord moet een string zijn
      #encoding met tokenizen van de zinnen
      print(text)

The output is: enter image description here

But when I remove the f.read()

I receive the expected out: enter image description here

I need to use the read() function, otherwise I cannot use the replace() function. Does anyone how to solve this issue?

3 Answers

f.read() converts the text file into a string. So if you iterate through a string, it will loop every character:

>>> for i in 'Hello World':
    print(i)

    
H
e
l
l
o
 
W
o
r
l
d
>>> 

Whereas without .read(), just f, would iterate line by line through the text file, it would be a sequence of strings (each line), it would be something like:

>>> for i in ['Hello', 'World']:
    print(i)

    
Hello
World
>>> 

Using text = f.read(), you are getting the whole text file into text. When you iterate over a string in Python, it gives you one character per iteration.

Since you want to continue using .read(), use splitlines():

text = f.read().splitlines()

Now, text is a list which you can freely iterate the same way you are already doing:

for line in text:

Other answers described the problem. However, the standard way to do this in python according to the best practices would be the following:

with open("glad.txt", "r") as file:
    for line in file:
        print(line)
        # do the stuff
Related