0

I wrote a program that reads from file and do some computation. I have a last function to add. It has to count in how many sentences specific word occurs. Here's the program itself:

# -*- coding: utf-8 -*-

from sys import argv # importing argv module so we can specify file to read

script, filename = argv # run program like this: python litvin.py filename.txt

txt = open(filename) # open file

text = txt.read() # get text from file


def count_letters(file):
    """ function that counts symbols in text without spaces """
    return len(file) - file.count(' ')
print "\nКількість слів в тексті: %d" % count_letters(text)

def count_sentences(file):
    """ function that counts sentences through finding '.'(dots)
            not quite cool but will work """
    return file.count('.')
print "\nКількість речень в тексті: %d" % count_sentences(text)

def longest_word(file):
    """ function that finds the longest word in the text """
    return max(file.split(), key=len)
print "\nНайдовше слово в тексті: '%s'" % longest_word(text)

def shortest_word(file):
    """ function that finds the longest word in the text """
    return min(file.split(), key=len)
print "\nНайкоротше слово в тексті: '%s'" % shortest_word(text)

def word_occurence(file):
   """ function that finds how many times specific word occurs in text """
    return file.count("ноутбук")
print "\nКількість разів 'ноутбук' зустрічається в тексті: %d" % 

word_occurence(text)



print "\n\n\t\tЩоб завершити програму натисніть 'ENTER' "
raw_input()
r_metal
  • 137
  • 1
  • 1
  • 8

1 Answers1

0

I would first get all sentences as list (hint: split text on .), and then loop through sentences and check if specific word is there or not.

Fejs
  • 2,734
  • 3
  • 21
  • 40
  • I splitted text as you suggest and now i have a list of items(sentences). How to look for specific word in each item? i tried .count but it won't work because it only finds items and not look in them for something – r_metal Nov 30 '16 at 13:37
  • You can iterate through list (using `for`) to get each sentence. That is where You use `count()`. – Fejs Nov 30 '16 at 14:21