使用Python 统计高频字数的方法

作者:Silent_Summer 时间:2023-07-19 09:20:18 

问题

(来自Udacity机器学习工程师纳米学位预览课程)

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

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

例如:


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

输出


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

解法


"""Count words."""

def count_words(s, n):
 """Return the n most frequently occuring words in s."""
 w = {}
 sp = s.split()
 # TODO: Count the number of occurences of each word in s
 for i in sp:
   if i not in w:
     w[i] = 1
   else:
     w[i] += 1

# TODO: Sort the occurences in descending order (alphabetically in case of ties)
 top = sorted(w.items(), key=lambda item:(-item[1], item[0]))
 top_n = top[:n]
 # TODO: Return the top n most frequent words.
 return top_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", 3)

if __name__ == '__main__':
 test_run()

小结

主要两个小技巧:

用split()将输入字符串按空格分开;

用sorted()函数对字典 先按值,再按键 进行排序,尤其是item:(-item[1], item[0])) 代表先对item的第二个元素 降序 排列(item 之前用了-),然后对第一个元素 升序 排列。多个元素的元组亦然。

来源:https://blog.csdn.net/cxsydjn/article/details/70991846

标签:Python,统计,字数
0
投稿

猜你喜欢

  • python中的property及属性与特性之间的优先权

    2023-02-03 02:36:12
  • 超好玩的"隔空操物"通过Python MediaPipe库实现

    2023-06-04 23:21:09
  • Python使用TextRank算法提取关键词

    2021-05-31 07:29:44
  • javascript动态添加单元格的脚本代码

    2023-09-02 05:21:26
  • 用户体验的另一种认识

    2007-10-25 12:36:00
  • 微信小程序实现上传图片功能

    2024-05-02 17:29:03
  • opencv+python实现均值滤波

    2023-10-21 15:00:58
  • python 中的 asyncio 异步协程

    2022-09-15 12:30:53
  • Python的OptionParser模块示例教程

    2023-01-03 05:21:03
  • 微信小程序学习之wxs使用教程

    2024-04-29 13:37:57
  • Python实现视频分解成图片+图片合成视频

    2022-12-14 05:26:12
  • js找出5个数中最大的一个数和倒数第二大的数实现方法示例小结

    2024-04-28 09:49:10
  • Python实现求解括号匹配问题的方法

    2023-08-02 08:05:47
  • python使用装饰器作日志处理的方法

    2021-08-17 03:20:32
  • Python实现PS滤镜的万花筒效果示例

    2023-11-15 10:17:25
  • Tensorflow 查看变量的值方法

    2022-12-14 09:36:47
  • 如何利用C#通过sql语句操作Sqlserver数据库教程

    2024-01-12 19:24:00
  • PyTorch使用GPU训练的两种方法实例

    2023-09-21 08:11:40
  • Python NumPy实用函数笔记之allclose

    2023-08-24 18:09:12
  • 交互设计实用指南系列(7)–避免迷路

    2010-01-23 09:52:00
  • asp之家 网络编程 m.aspxhome.com