2016-11-30 5 views
0

Ich schrieb ein Programm, das aus der Datei liest und einige Berechnungen durchführt. Ich habe eine letzte Funktion hinzuzufügen. Es muss zählen, in wie vielen Sätzen ein bestimmtes Wort vorkommt. Hier ist das Programm selbst:Wie man das Auftreten von Wörtern in Sätzen im Text zählt

# -*- 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() 

Antwort

0

Ich würde zuerst alle Sätze als Liste erhält (Tipp: split Text auf .), und dann die Schleife durch Sätze und prüfen, ob bestimmte Wort gibt oder nicht.

+0

Ich habe Text geteilt, wie Sie vorschlagen, und jetzt habe ich eine Liste von Elementen (Sätze). Wie nach bestimmten Wörtern in jedem Artikel suchen? ich versuchte .count, aber es wird nicht funktionieren, weil es nur Elemente findet und nicht in sie für etwas suchen –

+0

Sie können durch die Liste (mit 'for') durchlaufen, um jeden Satz zu bekommen. Dort benutzt du 'count()'. – Fejs

Verwandte Themen