The Artima Developer Community
Sponsored Link

Python Answers Forum
help...

1 reply on 1 page. Most recent reply: Apr 1, 2005 5:22 AM by Andy

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
ha ka

Posts: 1
Nickname: dreamer
Registered: Mar, 2005

help... Posted: Mar 31, 2005 9:50 AM
Reply to this message Reply
Advertisement
Hi everybody

How can I count how many words in a text file (in python)
Also, how can I find the length of a sentence also in a text file ( assume that each sentence end with e.g.(".", "?", "!" ... etc)where the legth of the sentence is the number of words in it.


---dreamer


Andy

Posts: 28
Nickname: adn
Registered: Jul, 2004

Re: help... Posted: Apr 1, 2005 5:22 AM
Reply to this message Reply
The number of words would be pretty straightforward, assuming that they're seperated only by spaces;

>>> len("here are my words".split())
4

So you just have to read all the words from the file, either all at once if the file isn't too big or do it line by line and count the number of words on each line, keeping a total.

For the second problem, you could split the file into words, and then (pseudo code)
for each word:
add 1 to our sentence length
if the word ends with ('.', '?', '!' etc.):
put the sentence length onto the end a list of lengths
set the sentence length counter back to 0.

You should then end up with a list of lengths, e.g. [11,5,9] would mean a file with sentences with 11, 5 then 9 words in.

But I'll leave the exact Python to you.

Flat View: This topic has 1 reply on 1 page
Topic: help making sublists Previous Topic   Next Topic Topic: cc problem

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use