仅供学习交流使用,请勿直接抄袭,请勿直接抄袭,请勿直接抄袭
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))
运行结果如下:不要搬我的运行截图,代码复制完直接就可以运行了,改改数据
点个👍吧