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

yipeiwu_com4年前Python基础

问题

(来自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 之前用了-),然后对第一个元素 升序 排列。多个元素的元组亦然。

以上这篇使用Python 统计高频字数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决django同步数据库的时候app models表没有成功创建的问题

问题描述: 在django中创建了一个app,而且在app中自定义创建了几个数据表,在同步的时候系统自带的表可以成功,但是models中的没有生效,而且进入对应app下的migratio...

Python补齐字符串长度的实例

如下所示: ljust(len,str)字符向左对齐,用str补齐长度 rjust(len,str)字符向右对齐,用str补齐长度 rjust(len,str)字符中间对齐,用s...

python反编译学习之字节码详解

前言 如果你曾经写过或者用过 Python,你可能已经习惯了看到 Python 源代码文件;它们的名称以.Py 结尾。你可能还见过另一种类型的文件是 .pyc 结尾的,它们就是 Pyth...

python argparser的具体使用

一.正常运行: 咱们随便写个文件: # test.py import argparse ap = argparse.ArgumentParser() ap.add_argumen...

Empty test suite.(PyCharm程序运行错误的解决方法)

Empty test suite.(PyCharm程序运行错误的解决方法)

运行程序test4_4.py时报错,Empty test suite. 查找资料发现原因: 默认情况下,PyCharm将检查以test开头的文件,它们是unittest.TestCas...