• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-08) 17次浏览 已收录 0个评论

今天小编就为大家分享一篇使用Python 统计高频字数的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

问题

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

用 Python 实现函数 count_w来源gao.dai.ma.com搞@代*码网ords(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单词。返回值是一个元组列表,包含出现次数最高的 n 个单词及其次数,即 [(, ), (, ), … ],按出现次数降序排列。

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

例如:

 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 统计高频字数的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用Python 统计高频字数的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址