检察院门户网站建设自查报告,google在线网页代理,wordpress公司网站模版,宿州精品网站建设词频统计是自然语言处理的基本任务#xff0c;针对一段句子、一篇文章或一组文章#xff0c;统计文章中每个单词出现的次数#xff0c;在此基础上发现文章的主题词、热词。
1. 单句的词频统计
思路#xff1a;首先定义一个空字典my_dict#xff0c;然后遍历文章#xf…词频统计是自然语言处理的基本任务针对一段句子、一篇文章或一组文章统计文章中每个单词出现的次数在此基础上发现文章的主题词、热词。
1. 单句的词频统计
思路首先定义一个空字典my_dict然后遍历文章或句子针对每个单词判断是否在字典my_dict的key中不存在就将该单词当作my_dict的key并设置对应的value值为1若已存在则将对应的value值1。
#统计单句中每个单词出现的次数
news Xi, also general secretary of the Communist Party of China (CPC) Central Committee and chairman of the Central Military Commission, made the remarks while attending a voluntary tree-planting activity in the Chinese capitals southern district of Daxing. def couWord(news_list): ##定义计数函数 输入句子的单词列表 输出单词-次数 的字典my_dict {} #空字典 来保存单词出现的次数for v in news_list:if my_dict.get(v):my_dict[v] 1else:my_dict[v] 1return my_dictprint(couWord(news.split ()))输出 {‘Xi,’: 1, ‘also’: 1, ‘general’: 1, ‘secretary’: 1, ‘of’: 4, ‘the’: 4, ‘Communist’: 1, ‘Party’: 1, ‘China’: 1, ‘(CPC)’: 1, ‘Central’: 2, ‘Committee’: 1, ‘and’: 1, ‘chairman’: 1, ‘Military’: 1, ‘Commission,’: 1, ‘made’: 1, ‘remarks’: 1, ‘while’: 1, ‘attending’: 1, ‘a’: 1, ‘voluntary’: 1, ‘tree-planting’: 1, ‘activity’: 1, ‘in’: 1, ‘Chinese’: 1, “capital’s”: 1, ‘southern’: 1, ‘district’: 1, ‘Daxing.’: 1} 以上通过couWord方法实现了词频的统计但是存在以下两个问题。
1未去除stopword
输出结果中保护’also’、‘and’、in’等stopword停止词停止词语与文章主题关系不大需要在词频统计等各类处理中将其过滤掉。
2未根据出现次数进行排序
根据每个单词出现次数进行排序后可以直观而有效的发现文章主题词或热词。
改进后的couWord函数如下
def couWord(news_list,word_list,N):#输入 文章单词的列表 停止词列表 输出Top N的单词my_dict {} #空字典 来保存单词出现的次数for v in news_list:if (v not in word_list): # 判断是否在停止词列表中if my_dict.get(v):my_dict[v] 1else:my_dict[v] 1topWord sorted(zip(my_dict.values(),my_dict.keys()),reverseTrue)[:N] return topWord加载英文停止词列表
stopPath rData/stopword.txt
with open(stopPath,encoding utf-8) as file:word_list file.read().split() #通过read()返回一个字符串函数再将其转换成列表 print(couWord(news.split(),word_list,5))输出 [(2, ‘Central’), (1, ‘voluntary’), (1, ‘tree-planting’), (1, ‘southern’), (1, ‘secretary’)] 2. 文章的词频统计
1单篇文章词频统计
通过定义读取文章的函数对其进行大小写转换等处理形成输入文章的单词列表。
def readFile(filePath): #输入 文件路径 输出字符串列表with open(filePath,encoding utf-8) as file:txt file.read().lower() #返回一个字符串,都是小写myTxt txt.split() #转换成列表 return myTxtfilePath rData/news/1.txt
new_list readFile(filePath) #读取文件
print(couWord(new_list,word_list,5))输出 [(17, ‘rights’), (14, ‘human’), (8, ‘united’), (7, ‘china’), (6, ‘resolution’)] 2多篇文章词频统计
需要使用os.listdir方法读取文件夹下的文件列表然后对文件逐一进行处理。
import os
folderPath rData/news #文件夹路径
tmpFile os.listdir(folderPath)
allNews []
for file in tmpFile: #读取文件newsfile folderPath // file #拼接完整的文件路径 \\ 转义字符allNews readFile(newsfile) #把所有的字符串列表拼接到allText中print(couWord(allNews,word_list,5)) 输出 [(465, ‘china’), (323, ‘chinese’), (227, ‘xi’), (196, “china’s”), (134, ‘global’)] 3中文文章的处理
对于中文文章的词频统计首先要使用jieba等分词器对文章进行分词并且加载中文的停止词列表再进行词频统计。