Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 531
Liza Darwesh Avatar asked Jan 03 '21 10:01

Liza Darwesh


People also ask

How can you use a for loop to read the entire content of a text file?

To do that, first, open the file using Python open() function in read mode. The open() function will return a file handler. Use the file handler inside your for-loop and read all the lines from the given file line by line. Once done,close the file handler using close() function.

How do you iterate through text in Python?

To iterate through lines in a file using Python, you can loop over each line in a file with a simple for loop. When reading files, the ability to read files sequentially line by line can be very useful. Reading text from a file is easy with the Python open() function.

How do you iterate data in Python?

In Python, there is not C like syntax for(i=0; i<n; i++) but you use for in n . They can be used to iterate over a sequence of a list , string , tuple , set , array , data frame . Given a list of elements, for loop can be used to iterate over each item in that list and execute it.

What is the use of for loop in Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.


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
>>> 
like image 77
U12-Forward Avatar answered Oct 21 '22 21:10

U12-Forward


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:
like image 3
MrCode Avatar answered Oct 21 '22 21:10

MrCode


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
like image 3
Juraj Bublinec Avatar answered Oct 21 '22 22:10

Juraj Bublinec