Python 统计字数的思路详解


本文摘自php中文网,作者不言,侵删。

这篇文章主要介绍了Python 统计字数的思路详解,文中还给大家提供了不借助第三方模块的解决方法,感兴趣的朋友一起看看吧

问题描述:

用 Python 实现函数 count_words(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单词。返回值是一个元组列表,包含出现次数最高的 n 个单词及其次数,即 [(<单词1>, <次数1>), (<单词2>, <次数2>), ... ],按出现次数降序排列。

您可以假设所有输入都是小写形式,并且不含标点符号或其他字符(只包含字母和单个空格)。如果出现次数相同,则按字母顺序排列。

例如:

1

print count_words("betty bought a bit of butter but the butter was bitter",3)

输出:

[('butter', 2), ('a', 1), ('betty', 1)]

解决问题的思路:

1. 将字符串s进行空白符分割得到所有的单词列表split_s,如:['betty', 'bought', 'a', 'bit', 'of', 'butter', 'but', 'the', 'butter', 'was', 'bitter']

2. 建立maplist,将split_s转化为元素为元组的列表形式,如:[('betty', 1), ('bought', 1), ('a', 1), ('bit', 1), ('of', 1), ('butter', 1), ('but', 1), ('the', 1), ('butter', 1), ('was', 1), ('bitter', 1)]

3. 合并maplist中元素,元组的第一个索引值相同,则将其第二个索引值相加。

// 备注:准备采用defaultdict。得到的数据如下:{'betty': 1, 'bought': 1, 'a': 1, 'bit': 1, 'of': 1, 'butter': 2, 'but': 1, 'the': 1, 'was': 1, 'bitter': 1}

4. 进行排序,按照key进行字母排序,得到如下:[('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('butter', 2), ('of', 1), ('the', 1), ('was', 1)]

5. 进行二次排序, 按照value进行排序,得到如下:[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]

6. 使用切片取出频率较高的*组数据

总结:在python3上不进行defaultdict进行排序结果也是正确的,python2上不正确。defaultdict本身是没有顺序的,要区分列表,所以必须进行排序。

也可尝试自己写,不借助第三方模块

解决方案1(使用defaultdict):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

from collections import defaultdict

"""Count words."""

def count_words(s, n):

  """Return the n most frequently occuring words in s."""

  split_s = s.split()

  map_list = [(k,1) for k in split_s]

  output = defaultdict(int)

  for d in map_list:

    output[d[0]] += d[1]

  output1 = dict(output)

  top_n = sorted(output1.items(), key=lambda pair:pair[0], reverse=False)

  top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True)

  return top_n[:n]

def test_run():

  """Test count_words() with some inputs."""

  print(count_words("cat bat mat cat bat cat", 3))

  print(count_words("betty bought a bit of butter but the butter was bitter", 4))

if __name__ == '__main__':

  test_run()

解决方案2(使用Counter)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from collections import Counter

"""Count words."""

def count_words(s, n):

  """Return the n most frequently occuring words in s."""

  split_s = s.split()

  split_s = Counter(name for name in split_s)

  print(split_s)

  top_n = sorted(split_s.items(), key=lambda pair:pair[0], reverse=False)

  print(top_n)

  top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True)

  print(top_n)

  return top_n[:n]

def test_run():

  """Test count_words() with some inputs."""

  print(count_words("cat bat mat cat bat cat", 3))

  print(count_words("betty bought a bit of butter but the butter was bitter", 4))

if __name__ == '__main__':

  test_run()

相关推荐:

Python实现计算圆周率π的值到任意位的方法示例

以上就是Python 统计字数的思路详解的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python实现百度语音识别api

关于Python类的实例详解

Python能做什么科学计算

Python如何切换文件夹

Python如何与excel结合

Python零基础新手入门小知识

Python gui是什么?

Python怎么把string变为hex

Python如何生成随机密码

Python对商城购物小程序的介绍

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...