zoukankan      html  css  js  c++  java
  • 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

    May we all proceed with wisdom and grace. https://www.cnblogs.com/YlnChen/
  • 相关阅读:
    如何使用Shiro
    ORACLE: 查询(看)表的主键、外键、唯一性约束和索引
    图片下载器类
    关于Android如何创建空文件夹,以及mkdir和mkdirs的区别
    图片二值化 和灰度处理方法
    InputSream转为String
    Bitmap Byte[] 互转
    静默安装/ 普通安装与root权限获取相关
    EventBus 3.0使用相关
    文件存储工具类
  • 原文地址:https://www.cnblogs.com/YlnChen/p/12586607.html
Copyright © 2011-2022 走看看