Count Words in a String (升级版)

Posted ylnchen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Count Words in a String (升级版)相关的知识,希望对你有一定的参考价值。

题目要求:

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(
)
        fileresult.write(str(count))
        fileresult.write(
)


# 调用函数:
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 (升级版)的主要内容,如果未能解决你的问题,请参考以下文章

Reverse Words in a String

186. Reverse Words in a String II

Reverse Words in a String leetcode

LeetCode Reverse Words in a String III

4.Reverse Words in a String III

Reverse Words in a string