博客
关于我
第7章-1 词频统计 (30分)【Python版本】
阅读量:193 次
发布时间:2019-02-28

本文共 1214 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要编写一个Python程序来统计一段英文文本中的所有不同单词,并找出词频最大的前10%的单词。以下是详细的解决方案。

方法思路

  • 读取输入:首先读取用户输入的文本,并去掉末尾的#符号。
  • 预处理文本:将所有非法字符替换为空格,然后将文本转换为小写字母。
  • 分割单词:将处理后的文本按空格分割成单词列表。
  • 截断单词:对超过15个字符的单词进行截断,只保留前15个字符。
  • 统计单词频率:使用字典记录每个单词的出现次数。
  • 排序单词:根据单词频率和字典序对单词进行排序。
  • 输出结果:输出所有不同单词的总数,随后输出词频最大的前10%的单词。
  • 解决代码

    import systext = sys.stdin.read().strip('#')# 替换非法字符为空格,并将所有字符转换为小写processed = []for c in text:    if c.isalnum() or c == '_':        processed.append(c.lower())    else:        processed.append(' ')text = ''.join(processed).strip()# 分割单词words = text.split()# 截断超过15个字符的单词for i in range(len(words)):    if len(words[i]) > 15:        words[i] = words[i][:15]# 统计单词频率word_counts = {}for word in words:    word_counts[word] = word_counts.get(word, 0) + 1# 按词频降序和字典序升序排序sorted_words = sorted(word_counts.items(), key=lambda x: (-x[1], x[0]))# 输出结果print(len(sorted_words))num_to_output = int(len(sorted_words) / 10)for i in range(num_to_output):    print(f"{sorted_words[i][1]}:{sorted_words[i][0]}")

    代码解释

  • 读取输入:使用sys.stdin.read()读取所有输入内容,并去掉末尾的#符号。
  • 预处理文本:遍历每个字符,保留字母、数字和下划线,将其转换为小写,其他字符替换为空格。
  • 分割单词:将预处理后的文本按空格分割成单词列表。
  • 截断单词:检查每个单词的长度,如果超过15个字符,则截断为前15个字符。
  • 统计单词频率:使用字典记录每个单词的出现次数。
  • 排序单词:根据频率降序和字典序升序对单词进行排序。
  • 输出结果:输出所有单词的数量,随后输出前10%的高频单词及其频率。
  • 转载地址:http://dbii.baihongyu.com/

    你可能感兴趣的文章
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    node exporter完整版
    查看>>