Python 查找输入文件中句子的最大和最小字数

Python 查找输入文件中句子的最大和最小字数,python,Python,我有一个问题,要求我找到文本文件中的最小和最大字数。我已经完成了五个问题中的三个,剩下的两个是关于最小值和最大值的问题,对此我没有任何解决方案。这是我的密码:谢谢你的帮助 您可以使用正则表达式查找如下单词: import re for line in open(thefilepath): re_word = re.findall(r"[\w'-]+",line) sentences = re.split(r"\.",k) for s in sentence: words_in_se

我有一个问题,要求我找到文本文件中的最小和最大字数。我已经完成了五个问题中的三个,剩下的两个是关于最小值和最大值的问题,对此我没有任何解决方案。这是我的密码:谢谢你的帮助

您可以使用正则表达式查找如下单词:

import re

for line in open(thefilepath):
 re_word = re.findall(r"[\w'-]+",line)
 sentences = re.split(r"\.",k)
 for s in sentence:
   words_in_sent=re.findall(r"[\w'-]+",k)
   summ+=len(word_in_sent)

print "Total number of sentences in the input file :{0}\n and Total number of words in the input file: {1}\n and average of words in each sentence is :{2} ".format(len(sentences),len(words),summ/len(sentences))
使用,用于此目的的数据类型

>>> from collections import Counter
>>> lines="""
... foo bar baz hello world foo
... a b c z d
... 0 foo 1 bar"""
>>> counter = Counter()
>>> 
>>> for line in lines.split("\n"):
...     counter.update(line.split())
... 
>>> print counter.most_common(1) #print max
[('foo', 3)]
>>> print counter.most_common()[-1] #print min
('hello', 1)
>>> print len(list(counter.elements()))  #print total words
15
我建议你看看
>>> from collections import Counter
>>> lines="""
... foo bar baz hello world foo
... a b c z d
... 0 foo 1 bar"""
>>> counter = Counter()
>>> 
>>> for line in lines.split("\n"):
...     counter.update(line.split())
... 
>>> print counter.most_common(1) #print max
[('foo', 3)]
>>> print counter.most_common()[-1] #print min
('hello', 1)
>>> print len(list(counter.elements()))  #print total words
15