zoukankan      html  css  js  c++  java
  • python练习册0004题

    在任意一个英文文档中,统计单词出现的次数,

    分析:

    本题不是很难,单词通常以空格隔开,但是有些单词后面跟一些特殊符号,只需把这些特殊符号替换掉就可以了,

    代码一

     1 import re
     2 
     3 file_name = 'code.txt'
     4 
     5 lines_count = 0
     6 words_count = 0
     7 chars_count = 0
     8 words_dict = {}
     9 lines_list = []
    10 
    11 with open(file_name, 'r') as f:
    12     for line in f:
    13         lines_count = lines_count + 1
    14         chars_count = chars_count + len(line)
    15         match = re.findall(r'[^a-zA-Z0-9]+', line)
    16 
    17         #正则 re.findall  的简单用法(返回string中所有与pattern相匹配的全部字串,返回形式为数组)语法:
    18         for i in match:
    19             # 只要英文单词,删掉其他字符
    20             line = line.replace(i, ' ')
    21         lines_list = line.split()
    22         for i in lines_list:
    23             if i not in words_dict:
    24                 words_dict[i] = 1
    25             else:
    26                 words_dict[i] = words_dict[i] + 1
    27 
    28 print('words_count is', len(words_dict))
    29 print('lines_count is', lines_count)
    30 print('chars_count is', chars_count)
    31 
    32 for k, v in words_dict.items():
    33     print( k, v)

    该代码有些啰嗦,网上找的,说下思路把,利用正则表达式找到所有的不是字母也不是数字的数据保存下来,然后再访问文本中的数据,将非字母和数字的数据替换为空

    弱弱的说一句,直接替换掉不就完了。

    代码二:

    这是本人所写的,较代码一稍微简洁些;

    import  re
    f=open("code.txt",'r')
    s=f.read()
    s.replace("[^a-zA-Z]",' ')
    s=s.split()
    word={}
    for i in s:
        if i not in  word:
            word[i]=1
        else:
            word[i]=word[i]+1
    for k,v in word.items():
        print(k,v)

    代码三:

    你以为你写的够简洁了吗?不,python早就帮你封装好函数了。

    点开才能看。

    import collections
    import re
     
    def calwords(path):
        word = []
        with open(path) as file:
            data = file.readlines()
        for line in data:
            word += re.split(' |,',line.strip('
    '))
        print(collections.Counter(word))
     
     
    if __name__ == '__main__':
        calwords('e://code.txt')
    View Code

    用到的方法说明

    正则 re.findall  的简单用法(返回string中所有与pattern相匹配的全部字串,返回形式为数组)
    语法:findall(pattern, string, flags=0)
    
    string的replace方法,用后一个参数替换字符串中的前一个参数。

    string.split方法
    str.split()
    
    单一分隔符,使用str.split()即可 
    
    str.split不支持正则及多个切割符号,不感知空格的数量
    
    re.split()
    
     多个分隔符,复杂的分隔情况,使用re.split
    
    原型: re.split(pattern, string, maxsplit=0)
    
    通过正则表达式将字符串分离。如果用括号将正则表达式括起来,那么匹配的字符串也会被列入到list中返回。maxsplit是分离的次数,maxsplit=1分离一次,默认为0,不限制次数。
    
    eg:
    
    >>>a='w w w'
    
    >>>import re
    
    1.空格分
    
    >>>re.split(r'[s]',a)
    
    ['w','w','w']
    
    2.只分割一次
    
    >>>re.split(r'[s]',a,1)
    
    ['w','ww']
    
    3.多个字符分割
    
    >>>c='w!w@w%w^w'
    
    >>>re.split(r'[!@%^],c)
    
    ['w','w','w','w','w']
    
    4.还原?:
    
    >>>re.split(r'(?:!@%^),c)
    
    ['w!w@w%w^w']
    
     

     

    描述
    Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
    
    注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
    couter 是一个容器,可以统计列表中元素的出现次数.
  • 相关阅读:
    笔记:多线程访问ConcurrentHashMap对key加锁
    根据第三列去重
    Correct the classpath of your application so that it contains a single, compatible version of org.apache.log4j.ConsoleAppender
    python 中将源配置为阿里
    criteria两个 判断
    git flow
    sqlmap用法详解
    MongoDB 入门
    MongoDB 手册
    OWASP TOP 10简单介绍
  • 原文地址:https://www.cnblogs.com/bianzhuo/p/9839113.html
Copyright © 2011-2022 走看看