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))

运行结果如下:不要搬我的运行截图,代码复制完直接就可以运行了,改改数据
在这里插入图片描述
点个👍吧

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

henu-于笨笨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值