2016-11-30 53 views
0

我編寫了一個程序,該文件從文件中讀取並進行一些計算。我有最後一個功能要添加。它必須計算特定單詞出現的次數。 下面是節目本身:如何統計文本中的單詞出現

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

回答

0

我將首先把所有的句子作爲列表(提示:拆分文本上.),然後遍歷的句子,並檢查特定的詞是有或沒有。

+0

我按照你的建議分割文本,現在我有一個項目(句子)的列表。如何在每個項目中查找特定單詞? 我試着.count,但它不會工作,因爲它只能找到項目,而不是在其中尋找東西 –

+0

你可以遍歷列表(使用'for')來獲得每個句子。這就是你使用'count()'的地方。 – Fejs

相關問題