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()
我按照你的建议分割文本,现在我有一个项目(句子)的列表。如何在每个项目中查找特定单词? 我试着.count,但它不会工作,因为它只能找到项目,而不是在其中寻找东西 –
你可以遍历列表(使用'for')来获得每个句子。这就是你使用'count()'的地方。 – Fejs