nath
nath

Reputation: 113

How to limit length of total words to read from a txt file

I have been trying to read a text documents easily using the code below, however I don't want to read the entire text documents, let's say the total length of the words in the text documents is 2,845.

for line in open('foo.txt', "r"):
        print(line)

i want to read the first 1,674 words from the documents

Thanks in advance

Upvotes: 1

Views: 193

Answers (1)

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2518

First of all, you should always use with open() to open and read a file, as the file gets closed automatically. In total it's less error prone and more readable.

Concerning your problem, here is a short snippet which should push you forward:

with open('foo.txt', 'r') as file:
    text = file.read().replace('\n', ' ')
    words = text.split(' ')
    char_limited_text = ' '.join(words[:1674]   

The above code works in three steps:

  1. It reads the whole text of the file into variable text
  2. It splits the text by single whitespaces
  3. Joining the words back together, but only taking the first 1674 words

If performance counts, there might be a better solution reading the file line by line and to keep track of how much words are read in already.

Upvotes: 2

Related Questions