栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 实验题目:统计词频给出一段文本,例如: “who have an apple apple is free free is money you know“,请统计单词出现的个数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 实验题目:统计词频给出一段文本,例如: “who have an apple apple is free free is money you know“,请统计单词出现的个数

python 实验题目:统计词频给出一段文本,例如: “who have an apple apple is free free is money you know”,请统计单词出现的个数

一种思路:两个单词之间夹着一个空格,所以空格数比单词数少一
但是又两种特殊情况:

 #对于空格很多不正常的情况:
    string1 = "who have an apple                apple is free free is money you know"
    # 对于文本中出现正常的标点符号的情况:
    string2 = "who have an apple , apple ,,,,,, is free free is money you know"

下面是解决方法:设置一个flag来判断

代码如下:

if __name__ == '__main__':
    count = 0#设置一个计数器,计数单词个数
    count1 = 0
    count2 = 0
    flag = 0#设置一个flag用来标记空格是否值出现一次
    string = "who have an apple apple is free free is money you know"
    #对于空格很多不正常的情况:
    string1 = "who have an apple                apple is free free is money you know"
    # 对于文本中出现正常的标点符号的情况:
    string2 = "who have an apple , apple ,,,,,, is free free is money you know"
    for s in string:
        if(("a" <= s and s <= "z") or ("A" <= s and s <= "Z")):
            flag = 0
        else:
            if(flag == 0):
                count += 1
                flag = 1
    for s in string1:
        if(("a" <= s and s <= "z") or ("A" <= s and s <= "Z")):
            flag = 0
        else:
            if(flag == 0):
                count1 += 1
                flag = 1
    for s in string2:
        if(("a" <= s and s <= "z") or ("A" <= s and s <= "Z")):
            flag = 0
        else:
            if(flag == 0):
                count2 += 1
                flag = 1
    print("正常文本情况下string的单词个数为:%s"%(count + 1))
    print("空格异常文本情况下string1的单词个数为:%s"%(count1 + 1))
    print("含有标点符号的情况下string2的单词个数为:%s"%(count2 + 1))

运行结果如下:不要搬我的运行截图,代码复制完直接就可以运行了,改改数据

点个吧

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/461257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号