coding: utf-8
# 1, 写一个名为 test1_count()的函数,函数的第一个参数为一个文本文件的位置,如‘data/document1.txt’。要求函数的功能包括:
# 1) 计算并打印出文本文件中所包含的词数(number of words),
# 2) 打印出不重复的词的数量(the number of unique words),
# 3) 打印出文本的行数,
# 4) 打印在文本中出现次数最多的十个词,及其出现的次数。
# 5) 返回词频列表,即文本中出现的所有词及每个词在文本中对应出现的次数
# In[1]:
import os
print ("%s" % os.getcwd())
# In[ ]:
#测试区间
# In[61]:
import string
def test1_count(a):
with open(a) as ff:
t=ff.readlines()
print(t)
# 1)统计单词数
words=0
for i in range(len(t)):
t[i]=t[i].strip() #去掉换行符\n
t[i]=''.join([j for j in t[i] if j not in string.punctuation]) #去标点
words=words+(t[i].count(' ')+1) #以空格为分割符,统计单词数
print(t)
print('所有单词数:words =',words) #所有单词数
# 2)打印不重复单词数
all=[]
for i in range(len(t)):
k=t[i].split(" ")
for j in range(len(k)):
all.append(k[j]) #创建了一个新的列表,解开原来列表的嵌套,把所有词放在一个为all的列表中
ndp_all=list(set(all)) #利用set不重复的特征,将所有不重复元素保存在ndp_all这个列表中
ndp_words=len(ndp_all)
print('所有不重复单词数:ndp_words =',ndp_words) #打印不重复单词数
文本分析基础练手题
最新推荐文章于 2021-06-06 22:14:20 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)