python 中文字数统计/分词

因为想把一段文字分词,所以,需要明确一定的词语关系。

在网上随便下载了一篇中文小说。随便的txt小说,就1mb多。要数数这1mb多的中文到底有多少字,多少分词,这些分词的词性是什么样的。

 

这里是思路

1)先把小说读到内存里面去。

2)再把小说根据正则表达法开始分词,获得小说中汉字总数

3)将内存中的小说每段POST到提供分词服务的API里面去,获取分词结果

4)按照API说明,取词

 

素材:

1、linux/GNU => debian/ubuntu 12.04/Linuxmint 13 Preferred
2、python
3、中文分词API, 这里我们使用的是 http://www.vapsec.com/fenci/
4、分词属性的说明文件下载 http://vdisk.weibo.com/s/qR7KSFDa9ON 或者 http://ishare.iask.sina.com.cn/f/68191875.html

 

这里已经写好了一个测试脚本。只是单个进程访问。还没有加入并发的测试。

在以后的测试中,我会加入并发的概念的。

下面是测试脚本 test.py

#!/usr/bin/env python
#coding: utf-8
import sys
import urllib
import urllib2
import os
import re
from datetime import datetime, timedelta


def url_post(word='My name is Jake Anderson', geshi="json"):
    url = "http://open.vapsec.com/segment/get_word"
    postDict = {
            "word":word,
            "format":geshi
    }
    
    
    postData = urllib.urlencode(postDict)
    request = urllib2.Request(url, postData)
    request.get_method = lambda : 'POST'
    #request.add_header('Authorization', basic)
    response = urllib2.urlopen(request)
    r = response.readlines()
    print r

if __name__ == "__main__":
    f = open('novel2.txt', 'r')
    # get Chinese characters quantity
    regex=re.compile(r"(?x) (?: [\w-]+ | [\x80-\xff]{3} )")
    count = 0
    for line in f:
        line = line.decode('gbk')
        line = line.encode('utf8')
        word = [w for w in regex.split(line)]
        count += len(word)
    #print count
    f = open('novel2.txt', 'r')
    start_time = datetime.now()
    for line in f:
        line = line.decode('gbk')
        line = line.encode('utf8')
        word2 = [w for w in regex.split(line)]
        print line
        url_post(line)
    end_time = datetime.now()
    tdelta = start_time - end_time
    print "It takes " + str(tdelta.total_seconds()) + " seconds to segment " + str(count) + " Chinese words!"
    print "This means it can segment " + str(count/tdelta.total_seconds()) + " Chinese characters per second!"

novel2.txt 是下载的小说。这个小说1.2MB大小。大约有580000字吧。

小说是GBK的格式,所以下载后,要转码成 utf-8的格式。

可以看到的终端效果大致是这样的。

把小说中所有的词,进行远程分词服务。

转载于:https://www.cnblogs.com/spaceship9/p/3611317.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值