美文网首页
Python中简单的词频统计

Python中简单的词频统计

作者: siro刹那 | 来源:发表于2017-04-12 21:22 被阅读4308次

用的是ipython notebook
1.框架是打开文件,写入文件

for line in open(in_file):
    continue
out = open(out_file, 'w')
out.write()```
2.简单的统计词频大致模板

def count(in_file,out_file):
#读取文件并统计词频
word_count={}#统计词频的字典
for line in open(in_file):
words = line.strip().split(" ")
for word in words:
if word in word_count:
word_count[word]+=1
else:
word_count[word]=1
out = open(out_file,'w')#打开一个文件
for word in word_count:
print word,word_count[word]#输出字典的key值和value值
out.write(word+"--"+str(word_count[word])+"\n")#写入文件
out.close()
count(in_file,out_file)```
一段很长的英文文本,此代码都是用split(" ")空格区分一个单词,显然是不合格的比如: "I will endeavor," said he,那么"I 和he,等等会被看成一个词,此段代码就是告诉你基本的统计词频思路。看如下一道题
1.在网上摘录一段英文文本(尽量长一些),粘贴到input.txt,统计其中每个单词的词频(出现的次数),并按照词频的顺序写入out.txt文件,每一行的内容为“单词:频次”
用的模板

#统计词频,按词频顺序写入文件
in_file = 'input_word.txt'
out_file = 'output_word.txt'
def count_word(in_file,out_file):
    word_count={}#统计词频的字典
    for line in open(in_file):
        words = line.strip().split(" ")
        for word in words:
            if word in word_count:
                word_count[word]+=1
            else:
                word_count[word]=1
    out = open(out_file,'w')
    for word in sorted(word_count.keys()):#按词频的顺序遍历字典的每个元素
        print word,word_count[word]
        out.write('%s:%d' % (word, word_count.get(word)))
        out.write('\n')
    out.close()
count_word(in_file,out_file)```
正则表达式的方法

import re
f = open('input_word.txt')
words = {}
rc = re.compile('\w+')
for l in f:
w_l = rc.findall(l)
for w in w_l:
if words.has_key(w):
words[w] += 1
else:
words[w] = 1
f.close()

f = open('out.txt', 'w')
for k in sorted(words.keys()):
print k,words[k]
f.write('%s:%d' % (k, words.get(k)))
f.write('\n')
f.close()```

相关文章

  • Python中简单的词频统计

    用的是ipython notebook1.框架是打开文件,写入文件 def count(in_file,out_f...

  • python词频统计实例

    项目概述 通过两个Python文件实现一个简单的词频统计。 本工程共有4个文件: file01:要统计的词频文件。...

  • python统计词频

    一、最终目的 统计四六级真题中四六级词汇出现的频率,并提取对应的例句,最终保存到SQL数据库中。 二、处理过程 1...

  • python统计词频

    一、使用re库进行识别 1、代码 2、参考 python--10行代码搞定词频统计python:统计历年英语四六级...

  • python 词频统计

    """Count words.""" def count_words(s, n): """Return the...

  • Python | 词频统计

    最近工作蛮忙的,就简单练习一下python基础吧。 本周的练习是词频统计,主要使用了以下几个函数: text.sp...

  • Python词频统计

    场景: 现在要统计一个文本中的词频,然后按照频率的降序进行排列

  • Python词频统计

    1.合并数据文件 2.词频统计

  • Python 进行词频统计

    1. 利用字典map实现 2.利用collections模块中的Counter对象 3. 算法:...

  • Python实现词频统计

    《百年孤独》词频统计 学习更多?欢迎关注本人公众号:Python无忧

网友评论

      本文标题:Python中简单的词频统计

      本文链接:https://www.haomeiwen.com/subject/bkhvattx.html