假设有一个年度报告的文本文件(in.txt)。实现数据统计功能:统计文件中出现次数最多的10个词语,作为主题词,要求词语不少于2个字符。统计结果写入文件out.txt
题目使用Counter类来统计单词出现的次数,并按降序输出出现最多的前10个单词及其出现次数
其实你们这些问题在csdn问答里经常反复出现,我发现有的时候连题干都没有变动,下次可以先搜索,没有结果在发言:
from collections import Counter
with open('in.txt', 'r') as file:
data = file.read().replace('\n', ' ')
words = data.split()
cleaned_words = [word.strip('.,!?"\\'').lower() for word in words]
word_counts = Counter(cleaned_words)
with open('out.txt', 'w') as file:
for word, count in word_counts.most_common(10):
if len(word) >= 2:
file.write(f"{word}: {count}\n")
统计现次数最多的10个词语代码如下:
count_word = {}
with open('in.txt') as file:
lines = file.readlines()
for line in lines:
words = line.split()
for w in words:
w = w.replace('.','') #把英文的标点符号去掉
if len(w)>=2:
count_word[w] = count_word.get(w,0)+1
#排序
count_word = sorted(count_word.items(),key= lambda x:x[1],reverse=True)
#输出前10个 保存到文件中
with open('out.txt', 'w') as f:
for item in count_word[0:10]:
print(item)
f.write(item[0] + ' ' + str(item[1]))
f.write('\n')
运行结果:
1、将自己的一个项目打包好后,希望别人能方便快速的安装使用自己的项目。那么就可以将项目依赖的所有包写到一个requirements.txt中。(注:可以是任意的.txt文件名,比如env.txt。)
2、下载了别人的项目代码,需要一键配置所有的依赖环境。
编写requirements.txt。比如一个示例如下:
--index https://pypi.douban.com/simple/
werkzeug
flask==2.0.1
Pillow
opencv-python
flask==2.0.1
可以使用nltk库或者collections库用于python文本数据统计。使用nltk库中的FreqDist类可以方便地实现统计某个文本文件中出现频率最高的10个词语的功能。同时,可以使用open()函数将结果输出到另一个文件out.txt中。
具体步骤如下: 1. 导入需要的库和模块,包括nltk和collections。
import nltk
from nltk import FreqDist
import collections
with open('input.txt','r',encoding='utf-8') as f:
text = f.read().lower()
tokens = nltk.word_tokenize(text)
# 剔除tokens中非单词词汇
tokens = [word for word in tokens if word.isalpha()]
# 统计每个单词在tokens中的出现次数
word_freq = collections.Counter(tokens)
# 将word_freq转换为FreqDist对象
freq_dist = FreqDist(word_freq)
# 统计出现频率最高的10个词语
top_words = freq_dist.most_common(10)
# 输出结果到控制台
for word, freq in top_words:
print('{}: {}'.format(word, freq))
with open('out.txt', 'w', encoding='utf-8') as f:
for word, freq in top_words:
f.write('{}: {}\n'.format(word, freq))
注意:在上述代码中,open()函数的第一个属性为文件的地址可以是相对位置或者绝对位置。对于防止编码问题,我们应该尽可能遵循UTF-8编码的规范,这样就能保证不会出现中文乱码的问题。
最终,整个代码应该为:
import nltk
from nltk import FreqDist
import collections
with open('input.txt','r',encoding='utf-8') as f:
text = f.read().lower()
tokens = nltk.word_tokenize(text)
# 剔除tokens中非单词词汇
tokens = [word for word in tokens if word.isalpha()]
# 统计每个单词在tokens中的出现次数
word_freq = collections.Counter(tokens)
# 将word_freq转换为FreqDist对象
freq_dist = FreqDist(word_freq)
# 统计出现频率最高的10个词语
top_words = freq_dist.most_common(10)
# 输出结果到控制台
for word, freq in top_words:
print('{}: {}'.format(word, freq))
# 输出结果到文件中
with open('out.txt', 'w', encoding='utf-8') as f:
for word, freq in top_words:
f.write('{}: {}\n'.format(word, freq))