python学习---单词计数统计

思路整理

1.打开文件,处理其中的每一行
2.将每个词添加到字典中更新其计数
3.显示输出,在此例中按频率高低进行排列

使用的python函数

Dict.items():所有键值对的元组列表
str.strip():用于移除字符串头尾指定的字符(默认为空格)
list.append(obj):用于在列表末尾添加新的对象
str.split():通过指定分隔符对字符串进行切片

函数定义

addWord:将每个单词添加到字典中
processLine:要处理行,还要完成剔除不同的字符,分割出单词等工作
prettyPrint:格式化的显示,将针对每种情况,将显示功能分离出来
main:使用主函数为主程序

addWord

def addWord(word,wordCountDict):
    '''Update the word frequency:word is the key,frequency is the value.'''
    if word in wordCountDict:
        wordCountDict[word] += 1
    else:
        wordCountDict[word] = 1

processLine

import sting
def processLine(line,wcDict):
    '''Process the line to get lowercase words to add to the dictionary.'''
    line = line.strip()
    wordList = line.split()
    for word in wordList:
        #ignore the '--' that is in file
       if word != '--':
           word = word.lower()
           word = word.strip()
           #get commas,periods and punctuation out as well

           word  = word.strip(string.punctuation)
           addWord(word,wcDict)

prettyPrint

def prettyPrint(wcDict):
    '''Print nicely from highest to lowest frequency.'''
    #create a list of tuple,(value,key)

    #valKeyList = [(val,key) for key,val in d.itemw()]

    valKeyList = []

    for key,val in wcDict.items():
        valKeyList.append((val,key))

    #sort method sorts on list's first element,here the frequency.
    #Reverse to get biggest first

    valKeyList.sort(reverse=True)
    print '%-10s%10s' %('Word','Count')
    print '_'*21
    for val,key in valKeyList:
        print '%-12s     %3d' %(key,val)

main

def main():
    wcDict = {}
    fobj = open('gettysbury.txt','r')
    for line in fobj:
        processLine(line,wcDict)
    print 'Length of the dictionary:',len(wcDict)
    prettyPrint(wcDict)

最终代码如下:

# __author__ == 'xjiao'
# -*- coding:utf-8 -*-

import string

def addWord(word,wordCountDict):
    '''Update the word frequency:word is the key,frequency is the value.'''

    if word in wordCountDict:

        wordCountDict[word] += 1 #如果单词在wordCountDict词典已存在,数量加1
    else:
        wordCountDict[word] = 1 #如果不存在,插入一条记录

def processLine(line,wcDict):
    '''Process the line to get lowercase words to add to the dictionary.'''

    line = line.strip() #去掉每行的空白
    wordList = line.split()  #去掉空白字符,分割字符

    for word in wordList:
        #ignore the '--' that is in file
        if word != '--':
            word = word.lower()
            word = word.strip()
           #get commas,periods and punctuation out as well

            word  = word.strip(string.punctuation)
            addWord(word,wcDict)


def prettyPrint(wcDict):
    '''Print nicely from highest to lowest frequency.'''
    #create a list of tuple,(value,key)

    #valKeyList = [(val,key) for key,val in d.itemw()]

    valKeyList = []

    for key,val in wcDict.items():
        valKeyList.append((val,key))

    #sort method sorts on list's first element,here the frequency.
    #Reverse to get biggest first

    valKeyList.sort(reverse=True)
    print '%-10s%10s' %('Word','Count')
    print '_'*21
    for val,key in valKeyList:
            print '%-12s     %3d' %(key,val)

def main():
    wcDict = {}
    fobj = open('gettysburg.txt','r')
    for line in fobj:
        processLine(line,wcDict)
    print 'Length of the dictionary:',len(wcDict)
    prettyPrint(wcDict)


if __name__ == "__main__":
    main()

输出结果如下:

D:\python\python.exe E:/python_project/gettysburg.py
Length of the dictionary: 136
Word           Count
_____________________
the               15
that              11
we                10
to                 9
here               9
of                 6
and                6
a                  6
nation             5
it                 5
have               5
in                 4
for                4
dedicated          4
who                3
us                 3
this               3
they               3
so                 3
shall              3
people             3
is                 3
great              3
dead               3
cannot             3
are                3
which              2
what               2
war                2
these              2
rather             2
our                2
or                 2
not                2
new                2
men                2
long               2
living             2
gave               2
from               2
field              2
far                2
devotion           2
dedicate           2
conceived          2
can                2
but                2
be                 2
years              1
world              1
work               1
will               1
whether            1
vain               1
upon               1
unfinished         1
thus               1
those              1
their              1
testing            1
task               1
take               1
struggled          1
should             1
seven              1
sense              1
score              1
say                1
resting-place       1
resolve            1
remember           1
remaining          1
proposition        1
proper             1
power              1
portion            1
perish             1
on                 1
now                1
note               1
nor                1
nobly              1
never              1
might              1
met                1
measure            1
lives              1
live               1
little             1
liberty            1
last               1
larger             1
increased          1
honored            1
highly             1
hallow             1
ground             1
government         1
full               1
freedom            1
four               1
fought             1
forth              1
forget             1
fitting            1
final              1
fathers            1
equal              1
engaged            1
endure             1
earth              1
do                 1
died               1
did                1
detract            1
created            1
continent          1
consecrated        1
consecrate         1
come               1
civil              1
cause              1
by                 1
brought            1
brave              1
birth              1
before             1
battle             1
as                 1
any                1
altogether         1
all                1
ago                1
advanced           1
add                1
above              1

Process finished with exit code 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容

  • 字符串的基本操作 字符串是Python中最常用的数据类型。我们可以使用引号('或")创建字符串。创建字符串很简单,...
    泷汰泱阅读 762评论 0 0
  • 1.1 列表的定义 List(列表) 是Python中使用最频繁的数据类型,在其他语言中通常叫做数组 专门用于存储...
    体面_5376阅读 811评论 0 0
  • capitalize 描述 将字符串的第一个字符大写 语法 实例 输出: islower 描述 判断字符串是否都为...
    安静点就睡吧阅读 1,201评论 0 4
  • 1 Python 字符串的 CRUD 操作 1.1 创建字符串 字符串是 Python 中最常用的数据类型。我们可...
    藕丝空间阅读 769评论 0 1
  • 不知道从什么时候起自己淡出了学校的各项外出培训活动。或许是自己年龄过大的原因。或许是早已厌倦了这样的培训。总觉...
    蜗牛_3982阅读 104评论 0 1