Python Show-Me-the-Code 第 0006 题 最重要的词

第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。



思路:切换到目标目录,然后遍历该目录下的txt文件,用正则表达式匹配响应的单词和数字,然后让Counter计算单词的词频,并认为排除掉stop word后出现最多的词是最重要的词。

注:stopword就是类似 a/an/and/are/then 的这类高频词,高频词会对基于词频的算分公式产生极大的干扰,所以需要过滤

部分代码引用Show-Me-the-Code 第四题中的统计单词代码



0006.最重要的词.py

#!/usr/bin/env python
#coding: utf-8
import re, os
from collections import Counter

# 目标文件所在目录
FILE_PATH = ‘/home/bill/Desktop‘

def getCounter(articlefilesource):
    ‘‘‘输入一个英文的纯文本文件,统计其中的单词出现的个数‘‘‘
    pattern = r‘‘‘[A-Za-z]+|\$?\d+%?$‘‘‘
    with open(articlefilesource) as f:
        r = re.findall(pattern, f.read())
        return Counter(r)

#过滤词
stop_word = [‘the‘, ‘in‘, ‘of‘, ‘and‘, ‘to‘, ‘has‘, ‘that‘, ‘s‘, ‘is‘, ‘are‘, ‘a‘, ‘with‘, ‘as‘, ‘an‘]

def run(FILE_PATH):
    # 切换到目标文件所在目录
    os.chdir(FILE_PATH)
    # 遍历该目录下的txt文件
    total_counter = Counter()
    for i in os.listdir(os.getcwd()):
        if os.path.splitext(i)[1] == ‘.txt‘:
            total_counter += getCounter(i)
    # 排除stopword的影响
    for i in stop_word:
        total_counter[i] = 0
    print total_counter.most_common()[0][0]

if __name__ == ‘__main__‘:
    run(FILE_PATH)


随便从BBC中国频道上选了几篇新闻进行测试

输出:

时间: 2024-08-05 04:14:08

Python Show-Me-the-Code 第 0006 题 最重要的词的相关文章

如何在python脚本开发做code review

在软件项目开发中,我们经常提到一个词"code review".code review中文翻译过来就是代码评审或复查,简而言之就是编码完成后由其他人通过阅读代码来检查代码的质量(可编译.可运行.可读.可维护.可复用),这些性质都比较抽象,但是一般都可以通过以下的检查点来实现: 检查代码的命名方式是否符合规范,代码的可读和可维护必须要求所有参与编码的同事使用的命名有统一的规范(注意每个人有自己的代码风格,但是要符合可读性的代码规范): 检查代码的注释,注释一般包括:1.类要有类用途和使用

面试Python工程师,这几道编码题有必要背背,Python面试题No8

第1题:列表[1,2,3,4,5],请使用map()函数输出[1,4,9,16,25],并使用列表推导式提取出大于10的数,最终输出[16,25]. map是python高阶用法,字面意义是映射,它的作用就是把一个数据结构映射成另外一种数据结构. map用法比较绕,最好是对基础数据结构很熟悉了再使用,比如列表,字典,序列化这些. map的基本语法如下: map(函数, 序列1, 序列2, ...) Python 2.x 返回列表. Python 3.x 返回迭代器. list = [1,2,3,

python核心编程第4章课后题答案(第二版75页)

4-1Python objects All Python objects have three attributes:type,ID,and value. All are readonly with a possible expection of the value(which can be changed only if the object is mutable). 4-5str()and repr() repr() is a built-in function while str() wa

[Python unittest] 3-Organizing test code

组织测试代码 前面已经了解到测试的原理和步骤,但只是默认类string的测试,如果是我们自己写的类改怎么测试呢? 如下 class Widget(object): def __init__(self,name,width=50,height=50): self.name = name self.width = width self.height = height def __repr__(self): return "Widget({0})".format(self.name) # 返

python 核心编程第六章课后题自己做的答案

6–6. 字符串.创建一个 string.strip()的替代函数:接受一个字符串,去掉它前面和后面的 空格(如果使用 string.*strip()函数那本练习就没有意义了) 1 'Take a string and remove all leading and trailing whitespace' 2 3 def newStrip(str): 4 'delete blanks around a string' 5 _end = len(str) 6 _start = 0 7 8 # de

python运行错误------Non-UTF-8 code

1.安装-----见:https://www.cnblogs.com/weven/p/7252917.html 本文转载于:http://blog.csdn.net/youyuyixiu/article/details/52886692 当python中的代码有中文时,有时会出现下图错误. 解决方法就是在程序的第一行加上 #coding=gbk 1 这样程序就正确啦,如下图. 原文地址:https://www.cnblogs.com/curo0119/p/8428807.html

python核心编程第2章课后题答案(第二版36页)

2-5 Loops and Numbers a) i = 0    while i <11:     print i    i += 1 b) for i in range(0,11): print i 2-6 Conditionals n =int( raw_input('enter a number:')) if n < 0: print 'negative' elif n > 0: print 'positive' else: print 'zero' 2-7 Loops and

python核心编程第5章课后题答案

5-8Geometry import math def sqcube(): s = float(raw_input('enter length of one side: ')) print 'the area is:', s ** 2., '(units squared)' print 'the volume is:', s ** 3., '(cubic units)'def cirsph(): r = float(raw_input('enter length of radius: ')) p

ubuntu下python脚本调用有道词典API实现命令行查词

#!/usr/bin/env python #coding=utf-8 '''   python使用有道词典的API来实现命令行查词 ''' import urllib2 import json import sys  reload(sys) sys.setdefaultencoding('utf-8') key = '1096888977' keyfrom = 'bloketest' doctype = 'json' u = 'http://fanyi.youdao.com/openapi.d