第0004道练习题_Python统计文本里单词出现次数

Python练习题第 0004 题

https://github.com/Show-Me-the-Code/show-me-the-code

第 0004 题:任一个英文的纯文本文件,统计其中的单词出现次数。

Talk is cheap, show you my code.

#! /usr/bin/env python
#! -*- coding: utf-8 -*-

from collections import OrderedDict
__author__ = ‘Sophie‘

class AppearanceCounter(object):
    def __init__(self):
        self.dict = {}

    def add_count(self,item):
        count = self.dict.setdefault(item, 0)
        self.dict[item] = count + 1

    def sort(self, desc = None):

        """~~~~~~Method 1~~~~~~~~~"""
        #result = sorted([(v,k) for (k,v) in self.dict.items()], reverse = desc)

        """~~~~~~Method 2~~~~~~~~~"""
        result = OrderedDict(sorted(self.dict.items(), key = lambda x: x[1], reverse = desc))

        return result

if __name__ == ‘__main__‘:
    ac = AppearanceCounter()
    file = open(‘/Users/Sophie/PycharmProjects/Practice_0004/CNN_News.txt‘,‘r‘)
    try:
        list_of_all_lines = file.readlines()
    finally:
        file.close()

    list_of_all_words = []
    temp = []

    for x in list_of_all_lines:
        temp = [t.strip(".?\"!,()‘") for t in x.lower().split()]
        list_of_all_words.extend(temp)

    for x in list_of_all_words:
        ac.add_count(x)

    r = ac.sort(True)
    print r

小知识点Get

1、setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

这个很好用,如果key已经存在于字典中,返回它对应的value,如果key不存在,则插入key和default value

2、我的字典里面有很多key-value对,如何排序?

http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-02 07:02:38

第0004道练习题_Python统计文本里单词出现次数的相关文章

用Hash Table(哈希散列表)实现统计文本每个单词重复次数(频率)

哈希表在查找方面有非常大应用价值,本文记录一下利用哈希散列表来统计文本文件中每个单词出现的重复次数,这个需求当然用NLP技术也很容易实现. 一.基本介绍 1.Hash Key值:将每个单词按照字母组成通过一个乘子循环运算得出一个小于29989的整数,29989是一个比较大的质数.0~29989即为Key值. 2.哈希函数: 1 //哈希函数 2 unsigned int hashIndex(const char* pWord) //返回hash表的索引(即hash指针数组的下标) 3 { 4 a

Python 基础 - 统计文本里单词的个数以及出现的次数

# -*- coding:utf-8 -*- #author:V def tol (file1,gui): #写一个方法,定义文件,or 匹配规则 import re patt = re.compile(gui) #print(type(patt)) f = open(file1,'r') #print(type(f)) try: return len(patt.findall(f.read())) #findall接受str类型,之前我把file 类型房间去,结果傻逼了 finally: #不

PHP统计字符串里单词查询关键字

<?function full_count_words($str) {     //返回完整数组,包含字符串里每个单词 $words = str_word_count($str,1);     $result = array();     foreach ($words as $w) {         $lw = strtolower($w);         //判断单词是否是第一次出现,是则设置为1,否则就增加1 if (!(isset($result[$lw]))) {         

第0011道练习题_Python下载&lt;杉本有美&gt;图片

Python练习题第 0011题 https://github.com/Yixiaohan/show-me-the-code 用 Python 写一个爬图片的程序,爬这个链接里的日本妹子图片 :-) http://tieba.baidu.com/p/2166231880 如果html是这样子的话: <img...>...</img> <img...>...</img> <img...>...</img> 用BeautifulSoup是

第0000道练习题_Python简单图像处理

Python练习题第 0000 题 https://github.com/Show-Me-the-Code/show-me-the-code 将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果. Talk is cheap, show you my code. #! /usr/bin/env python # -*- coding:utf-8 -*- from PIL import Image, ImageDraw, ImageFont __author_

awk统计文本里某一列重复出现的次数

比如这样的场景:现在有一个文本,里面是这样的内容: NOTICE: 12-14 15:11:13:  parser. * 6685  url=[http://club.pchome.net/thread_1_18_7283270___TRUE.html] get_tm=115 PAGE=15471[Z]:59066 css_tm=1043 css_res=0/4[0] CONT=3230[Z]:4797 LINK=6095[Z]:22834 TITL=61 PtDef=7 UnifyUrl=47

采用二叉搜索树来统计文本中单词出现的频率

把几个主要的函数组合起来即可: 1.从文本读取单个单词(去掉空格,特殊符号等) 2.用读出来的单词去更新搜索二叉树的节点(涉及二叉树的构建问题,递归) 3.中序遍历,来递归打印二叉树的每个节点 代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAXWORD 1000 //单词出现频率的统计哦 struct tnode { cha

Hadoop:统计文本中单词熟练MapReduce程序

这是搭建hadoop环境后的第一个MapReduce程序: 基于python的脚本: 1 map.py文件,把文本的内容划分成单词: #!/bin/pythonimport sys for line in sys.stdin:    data_list = line.strip().split()    for i in range(0, len(data_list)):        print data_list[i]         2 reduce文件,把统计单词出现的次数: #!/bi

shell统计文本中单词的出现次数

Ubuntu14.04 给定一个文本,统计其中单词出现的次数 # solution 1 grep与awk配合使用,写成一个sh脚本 fre.sh sh fre.sh wordfretest.txt #! /bin/bash# solution 1 if [ $# -eq 0 ] then echo "Usage:$0 args error" exit 0 fi if [ $# -ge 2 ] then echo "analyse the first file $1"