Ask coding questions

← Back to all posts
How can I get Python to print a specified number of words in a text file?
bennyrobert (47)

Hello, I have a text file, and my program needs to print a number of words the user specifies (out of 100 paragraphs). I also need to know how I can get it to print a specified number of sentences.

It doesn't really work at the moment, it only prints a random part of my text file when I press run.



use slicing, like this.

something = "something"

use it in your will.
Try that. It should work.

Coder100 (17026)
words = "hello world"

print(len(words.split(" ")))

as you can see that will give you 2, because there are two words

bennyrobert (47)

So would that work if the words variable were to equal a text [email protected]

Coder100 (17026)

it works for all strings. Reading a text file gives you a string. @bennyrobert

bennyrobert (47)

What should I do about this error? it's not even showing me what part is wrong. @Coder100

Coder100 (17026)

you used a ] instead of a ) lol @bennyrobert

Coder100 (17026)

and your current error is because print is a function


lol did you just give up and try to use tutorials

bennyrobert (47)

Believe me, I've tried everything. I have a tendecy for over-complicating things, this might not even be the right way to go about it. @Coder100

bennyrobert (47)

But I'll get it all fixed, and hopefully it'll work.

KHZ (122)

@bennyrobert If you want to print the anything from the start you can use this code and replace ____ with the name of the variable you want to print:

f = open("file.txt", "r")

sentences = f.split("\n")
words = file.split()

no_of_words = int(input())

for i in range(no_of_words):
  print (____)