python 统计TXT中的英文词频

每句话会出现英文下的句号(.),当然也可能出现其他标点符号(,! ?等等)。

先处理句号和逗号。

如果不进行处理

>>> "and port 4 communicateswith the SGMII4 module.".split()

['and', 'port', '4', 'communicates','with', 'the', 'SGMII4', 'module.']

可以发现句号和某个合在一起组成了一个新的字符串。

用字符串的replace方法来去掉句号。

>>> "and port 4 communicateswith the SGMII4 module.".replace('.','').split()

['and', 'port', '4', 'communicates','with', 'the', 'SGMII4', 'module']

如果句子中既有句号又有逗号

>>> "and port 4 communicates,with the SGMII4 module.".replace('.','').split()

['and', 'port', '4', 'communicates,','with', 'the', 'SGMII4', 'module']

>>> "and port 4 communicates,with the SGMII4 module.".replace('.','').replace(',','').split()

['and', 'port', '4', 'communicates','with', 'the', 'SGMII4', 'module']

当要统计的文本中标点符号太多时,可以采用如下方式。

先import string,string模块中有punctuation属性,它包含了所有的标点符号。

       fori in string.punctuation:

              r2=r2.replace(i,'')

       r2=r2.split()

得到的为r2为列表形式,现在要统计词频,很容易想到字典这用数据结构。

 

frequencies = {}

for word in r2:

   frequencies[word] += 1

python会抛出一个KeyError 异常,因为字典索引之前必须初始化,可以用下面的方法解决

 

for word in r2:

   try:

       frequencies[word] += 1

   except KeyError:

       frequencies[word] = 1

当然也可以使用setdefault()方法

Dict(一个字典变量).setdefault()方法(字典方法)接收两个参数,第一个参数是key的名称,第二个参数是默认值。假如字典中不存在给定的key,则返回参数中提供的默认值,并创建一个key---value;反之,则返回字典中保存的值。

>>> frequencies = {}

>>> for word in r2:

       frequencies[word]= frequencies.setdefault(word,0)+1

 

当然,collections.defaultdict也可以轻松的解决这个问题

 

from collections import defaultdict

frequencies = defaultdict(int) #传入int()函数来初始化

for word in r2:

   frequencies[word] += 1

collections.defaultdict可以接受一个函数作为参数来初始化。什么意思呢,看上面的例子,我们想要frequencies[word]初始化为0,这时就可以用一个int()函数作为参数出给defaultdict,我们不带参数调用int(),int()就会返回一个0值

完整代码


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值