I have a text file which contains 100 sentences. i want to write a python script that will count average sentence length (in words) from a text file contains 100 sentences. Thanks
how to count average sentence length (in words) from a text file contains 100 sentences using python
Asked
Active
Viewed 1.4k times
-6
-
4What does your code look like? – Hyperboreus Dec 20 '12 at 10:37
-
i wanted the code. i am new to python. couldn't find the solution over net. – Wild Freelancer Dec 20 '12 at 15:34
3 Answers
3
wordcounts = []
with open(filepath) as f:
text = f.read()
sentences = text.split('.')
for sentence in sentences:
words = sentence.split(' ')
wordcounts.append(len(words))
average_wordcount = sum(wordcounts)/len(wordcounts)

snurre
- 3,045
- 2
- 24
- 31
0
this should help you out. but this is basic stuff, you should have at least tried something yourself.
this code assumes each sentence is on a new line.
if that is not the case, you can either correct the code, or reflect that in your question, which is unclear about this.
def read_lines_from_file(file_name):
with open(file_name, 'r') as f:
for line in f:
yield line.strip()
def average_words(sentences):
counts = []
for sentence in sentences:
counts.append(sentence.split())
return float(sum(counts)/len(counts))
print average_words(read_lines_from_file(file_name))

Inbar Rose
- 41,843
- 24
- 85
- 131