python统计文档词数

题目1

莎士比亚的经典悲剧Hamlet,获取该故事的文本文件,保存为hamlet.txt,统计该故事的英文词频。
提示:
(1)处理文本,统一格式。英文单词一般以空格、标点符号或特殊符号进行分割,可以将标点符号或特殊符号都替换成空格(使用 .replace()方法),之后进行单词提取。(注意英文单词字母大小写问题 .lower())
(2)对单词进行计数。使用字典count,其键值分别为单词word及出现的次数,统计次数可使用count[word] = count.get(word,0) + 1
(3)对单词统计值从高到低排序输出,例如,输出qian10个高频词。字典美欧顺序,可借助列表结构,使用sort()方法配合lambda函数实现排序。

Items = list(count.items()) #将字典转换为列表,思考下该列表元素的结构

Item.sort(key = lambda x: x[1], reverse = True) #以记录的第二列即次数进排序

编写程序,观察输出结果,高频单词中虚词居多,为了能够体现文章含义,可以建立一个排除库excludes,将虚词排除掉,再观察输出结果。

# 定义需要排除的虚词列表
excludes = {'the', 'and', 'of', 'to', 'in', 'a', 'that', 'is', 'for', 'it', 'with', 'on', 'as', 'was', 'by', 'at', 'an',
            'be', 'this', 'which', 'or', 'from', 'but', 'not', 'are', 'have', 'they', 'you', 'one', 'had', 'all', 'we',
            'can', 'her', 'has', 'there', 'been', 'if', 'more', 'when', 'will', 'would', 'who', 'so', 'out', 'up',
            'their', 'what', 'about', 'into', 'than', 'its', 'some', 'could', 'them', 'these', 'may', 'other', 'then',
            'do', 'only', 'time', 'new', 'like', 'any', 'now'}


def count_words(file_name):
    # 打开文件并读取内容
    with open(file_name, 'r') as file:
        text = file.read()

    # 将所有非字母字符替换为空格,并转换为小写
    text = text.lower().replace(',', ' ').replace('.', ' ').replace('!', ' ').replace('?', ' ').replace(':',
                                                                                                        ' ').replace(
        ';', ' ').replace('-', ' ').replace('_', ' ').replace('(', ' ').replace(')', ' ').replace('[', ' ').replace(']',
                                                                                                                    ' ').replace(
        '{', ' ').replace('}', ' ').replace('"', ' ').replace("'", ' ')

    # 分割文本为单词列表
    words = text.split()

    # 统计单词出现次数,排除虚词
    count = {}
    for word in words:
        if word not in excludes:
            count[word] = count.get(word, 0) + 1
    return count

def print_top_words(count, num=10):
    # 将字典转换为列表并按值排序
    items = list(count.items())
    items.sort(key=lambda x: x[1], reverse=True)
    # 输出前num个高频词
    for word, freq in items[:num]:
        print(f'{word}: {freq}')

# 主程序
if __name__ == "__main__":
    hamlet_count = count_words('hamlet.txt')
    print("Top 10 words in Hamlet (excluding common words):")
    print_top_words(hamlet_count, 10)
题目2

中文词频统计。《三国演义》人物出场统计。
(1)使用jieba库进行分词
(2)进行词频统计
观察程序运行结果,排除与人名无关的词。对程序进行完善,同一人物有不同的名字,需要整合处理。

import jieba
from collections import Counter

# 假设我们有一个简化版的人物别名映射
name_aliases = {
    "刘备": ["玄德", "刘玄德"],
    # ...其他人物及其别名
}

# 读取文本文件
with open('三国演义.txt', 'r', encoding='utf-8') as file:
    text = file.read()

# 使用jieba分词
words = jieba.lcut(text)

# 初始化Counter对象
word_counts = Counter(words)

# 整合人物别名
for name, aliases in name_aliases.items():
    for alias in aliases:
        word_counts[name] += word_counts.pop(alias, 0)

# 排除一些常见非人名词语
exclude_words = {"的", "在", "了", "和", "是", "有", "我", "他", "这", "那", "不", "一个", "人", "说"}
word_counts = Counter({word: count for word, count in word_counts.items() if word not in exclude_words})

# 获取前10个高频词(确保word_counts仍然是Counter对象)
top_characters = word_counts.most_common(10)

# 输出结果
print("人物出场统计(前10名):")
for character, count in top_characters:
    print(f"{character}: {count}次")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值