首页 > 编程语言 > 详细

【python小练】0004

时间:2016-03-24 16:02:31      阅读:201      评论:0      收藏:0      [点我收藏+]

第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。

 

先回忆一下各种括号的用途:

() tuple

[] list

{} dict

([]) set——需要一个list作为输入合集

 

code:

# coding = utf-8
__author__= liez

import re
def num(path):
    with open(path, r) as file:
        data=file.read()
        print(data)
        words=re.compile([a-zA-Z0-9]+) #compile好像是必须用的,用来格式转换什么的,然后才能进行匹配之类的操作
        dict={}

        for x in words.findall(data):
            if x not in dict:
                dict[x]=1
            else:
                dict[x]+=1

        print(dict)

num(liez.txt)

结果如下。

I am liez.
I am a player.
I love programming.
{love: 1, I: 3, player: 1, programming: 1, a: 1, am: 2, liez: 1}

 

背单词的时候看到有人统计了GRE高频词,记得好像也是拿python写的。

把上面那个程序改一下也能起到同样效果,几个改动:

1. 原先用dict输出,现在迁到list里,因为dict好像没法排序,list可以用sorted

2. 打开并写入文件liez.xls

import re
def num(path):
    with open(path, r) as file:
        data = file.read()
        print(data)
        words = re.compile([a-zA-Z0-9]+)

        dict = {}
        for x in words.findall(data):
            if x not in dict:
                dict[x] = 1
            else:
                dict[x] += 1
        for x in dict:
             print(x, dict[x])

        list=[]
        for key,value in dict.items():
            list.append((key, value)) #注意是两个括号,因为append只能添加一个参数
        list.sort(key = lambda t:t[1], reverse = True)
        for x in list:
            print(x[0], x[1])

        with open(liez.xlsx, w) as file:
            for x in list:
                k= .join([str(j) for j in x]) #join可以添加string,所以要转换list里的元素成str
                file.write(k+\n)
            file.close()

num(liez.txt)

打开liez.xls能看到txt文件里的单词出按现次数从高到低排列,但是单词和出现次数没分列,我不知道怎么把他们弄分列。

不过操作excel文件专门有一个xlwt module,可以指定写入文件的行和列。改天写个单词软件再用吧(毕竟没找的称心的 ̄へ ̄)。

 

【python小练】0004

原文:http://www.cnblogs.com/liez/p/5315675.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!