码迷,mamicode.com
首页 > 其他好文 > 详细

Count Words in a String (升级版)

时间:2020-03-28 13:03:38      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:ado   执行   use   enc   extra   other   ret   item   count   

题目要求:

read these strings in from a text file and generate a summary.

 

import os
def count_words(file):
    try:
        f = open(file, r, encoding=UTF-8)
    except IOError as s:
        print(s)
        return None
    # try,except语句:用来捕获异常,try:尝试执行的代码,except:出现错误的处理
    try:
        buffer = f.read()
    except:
        print(Read File Error!)
        return None
    (filepath, filename) = os.path.split(file)
    # 使用os模块的path.split函数获得传入文件的路径名与文件名
    f.close()
    buffer = buffer.lower()
    # 全部换成小写,以免后面大小写按照不同字符处理
    words = buffer.split( )
    # 按空格分割文本,针对英文单词,目前还不知道怎么分割一个字一个字得分割汉字
    counts = {}
    # (),[],{}分别代表元组,列表,字典,这里是创建一个空字典接收后面的循环计数器结果
    sumcount = 0
    for word in words:
        counts[word] = counts.get(word, 0) + 1
        sumcount = sumcount + 1
    # 循环计数器:
    # dict.get(key, default=None)
    # key -- 字典中要查找的键。
    # default -- 如果指定键的值不存在时,返回该默认值。
    # 当word不在words时,返回值是0,当word在words中时,返回+1,以此进行累计计数。
    items = list(counts.items())
    items.sort(key=lambda x: x[1], reverse=True)
    # 将字典按value的值进行排序
    fileresult = open(os.path.join(filepath, "result.txt"), w)
    # 在传入文件的路径之下,创建一个新的result文件,具有可写的属性
    for i in range(5):
        word, count = items[i]
        fileresult.write(word)
        # f.write每次只能传入一个值,有没有更简洁的写法呢?欢迎评论
        fileresult.write(\n)
        fileresult.write(str(count))
        fileresult.write(\n)


# 调用函数:
count_words("C:\\Users\\cccc\\Desktop\\hamlet.txt")

原始文件为:

Oh they say people come say people go
This particular diamond was extra special
And though you might be gone and the world may not know
Still I see you celestial
When I should but I can‘t let you go
But when I‘m cold cold
When I‘m cold cold
There‘s a light that you give me when I‘m in shadow
There‘s a feeling within me an everglow
Like brothers in blood sisters who ride
And we swore on that night we‘d be friends ‘til we die
But the changing of winds and the way waters flow
Life is short as the falling of snow
And now I‘m gonna miss you I know
But when I‘m cold cold
In water rolled salt
I know you‘re with with me and the way you will show
And you‘re with me wherever I go
And you give me this feeling this everglow
Oh what I wouldn‘t give for just a moment to hold
Becasue I live for this feeling this everglow
So if you love someone you should let them know
Oh the light that you give me will everglow

 

结果为:

you
10
i
7
the
6
me
6
i‘m
5

Count Words in a String (升级版)

标签:ado   执行   use   enc   extra   other   ret   item   count   

原文地址:https://www.cnblogs.com/YlnChen/p/12586607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!