栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在.txt文件中找到最常用单词的Python程序,必须打印单词及其计数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在.txt文件中找到最常用单词的Python程序,必须打印单词及其计数

如果您需要计算段落中的单词数,则最好使用正则表达式。

让我们从一个简单的例子开始:

import remy_string = "Wow! Is this true? Really!?!? This is crazy!"words = re.findall(r'w+', my_string) #This finds words in the document

结果:

>>> words['Wow', 'Is', 'this', 'true', 'Really', 'This', 'is', 'crazy']

请注意,“是”和“是”是两个不同的词。我的猜测是,您希望对它们进行相同的计数,因此我们可以将所有单词大写,然后对其进行计数。

from collections import Countercap_words = [word.upper() for word in words] #capitalizes all the wordsword_counts = Counter(cap_words) #counts the number each time a word appears

结果:

>>> word_countsCounter({'THIS': 2, 'IS': 2, 'CRAZY': 1, 'WOW': 1, 'TRUE': 1, 'REALLY': 1})

你准备好了吗?

现在,我们需要做的与上次完全相同,只是这次我们正在读取文件。

import refrom collections import Counterwith open('your_file.txt') as f:    passage = f.read()words = re.findall(r'w+', passage)cap_words = [word.upper() for word in words]word_counts = Counter(cap_words)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639983.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号