Python实现一篇txt文章的词频统计:文件读取+字典

上周tensorflow小组作业记录一下,初始代码来自周帜老师我们可爱的gg,我做了一些输出调整,并制作了原理讲解,以下:所见即所得。
操作:把txt文件和.py文件保存在一个文件夹下,接着复制粘贴代码就可以所见即所得啦
思路将在以下的图片中分步讲明,也可以拉到底直接看代码

在这里插入图片描述
在这里插入图片描述在这里插入图片描述在这里插入图片描述
代码:

#完成词频的统计,需要将dictTxt.txt文件和程序文件放在同一文件夹中
import operator
import os
#打开文件
speech_text=''
try:
	f = open(os.path.abspath('dictTxt.txt'),'r')
	speech_text = f.read()
	f.close()
except:
	print("File Open Error.")

print('Speech text:')
print(speech_text)

#将单词转换为小写
speech = speech_text.lower().split()

print('After lower()&split():')
print(speech)

# 利用字典进行处理
dic = {}
for word in speech:
	if word not in dic:
		dic[word]=1
	else:
		dic[word]+=1

print('Dic:')
print(dic)

#对字典中的进行排序
swd = sorted(dic.items(),key=operator.itemgetter(1),reverse=True)
print(swd)

我还写了另外一种代码写法,但是没有上一种好,也粘上来一下

#完成词频的统计,需要将dictTxt.txt文件和程序文件放在同一文件夹中
import operator
#打开文件
try:
	f = open('dictTxt.txt','r')
	speech_text = f.read()
finally:
	if f:
		f.close()
#将单词转换为小写
speech = speech_text.lower().split()
#print(speech)
# 利用字典进行处理
dic = {}
for word in speech:
	if word not in dic:
		dic.update({word:1})
	else:
		dic.update({word:dic[word]+1})

#对字典中的进行排序
swd = sorted(dic.items(),key=operator.itemgetter(1),reverse=True)
print(swd)

p.s.
附上dictTxt.txt文件内容:
My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you’ve bestowed, mindful of the sacrifices borne by our ancestors.
I thank President Bush for his service to our nation – (applause) – as well as the generosity and cooperation he has shown throughout this transition.
Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often, the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because we, the people, have remained faithful to the ideals of our forebears and true to our founding documents.
So it has been; so it must be with this generation of Americans.
That we are in the midst of crisis is now well+++ understood. Our nation is at war against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nat

  • 4
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: 以下是一个简单的Python词频统计代码: ```python import re from collections import Counter def word_count(text): words = re.findall(r'\w+', text.lower()) return Counter(words) text = "This is a sample text for word count. This text is used to count the frequency of words in a text." print(word_count(text)) ``` 输出结果为: ``` Counter({'this': 2, 'text': 2, 'is': 2, 'a': 1, 'sample': 1, 'for': 1, 'word': 1, 'count': 1, 'used': 1, 'to': 1, 'the': 1, 'frequency': 1, 'of': 1, 'words': 1, 'in': 1}) ``` ### 回答2: Python词频统计代码可以通过使用字典实现。以下是一个简单的示例代码: ```python def word_frequency(text): # 创建一个空字典用于存储单和其出现的次数 word_dict = {} # 将文本拆分为单列表 words = text.split() # 遍历所有单 for word in words: # 检查单是否已存在于字典中 if word in word_dict: # 如果单已存在,则将其计数加1 word_dict[word] += 1 else: # 如果单不存在,则将其添加到字典,并设置计数为1 word_dict[word] = 1 # 返回字典,其中键是单,值是出现的次数 return word_dict # 示例用法 text = "Python是一种流行的编程语言, Python的语法简单易学。Python的应用广泛,可以进行数据分析、人工智能等" result = word_frequency(text) print(result) ``` 以上代码将会输出如下结果: ``` {'Python是一种流行的编程语言,': 1, 'Python的语法简单易学。Python的应用广泛,可以进行数据分析、人工智能等': 1} ``` 这里只是一个简单的示例,实际应用中可能会涉及更复杂的文本处理和数据清洗过程。 ### 回答3: Python词频统计是一种通过Python编程语言实现的文本处理技术。它可以用于统计一篇文章或一段文字中各个语出现的频率,以便后续的文本分析和挖掘。以下是一个简单的Python词频统计代码示例: ```python # 导入所需的模块 import re from collections import Counter # 读取文本文件 with open('text.txt', 'r') as file: text = file.read() # 使用正则表达式提取单 words = re.findall(r'\w+', text.lower()) # 统计频 word_counts = Counter(words) # 输出频结果 for word, count in word_counts.most_common(10): print(word, count) ``` 上述代码首先导入了`re`和`Counter`两个模块,分别用于正则表达式和计数功能。然后使用`with open`语句打开并读取文本文件中的内容。接着使用正则表达式`re.findall()`方法提取出所有的单,并将它们转换为小写形式。 接下来,利用`Counter`类统计单出现的频率,生成一个词频统计结果字典`word_counts`。 最后,通过遍历`word_counts`字典中的前10项,并使用`most_common()`方法按照频降序排列,输出每个单及其对应的频率。 以上就是一个简单的Python词频统计代码示例,通过这段代码,可以方便地对文本进行词频统计,并获得出现频率最高的前几个语。具体的使用场景和需求,可以根据实际情况进行参数的调整和代码的扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值