python - 如何使用 Python 制作字数计数器程序?
问题描述
我需要创建一个读取文本文件并打印以下内容的程序:
- 文本中的所有唯一词
- 它们在文本中出现的次数
- 总字数
from collections import Counter
count = 0
file = open(r"sample_input.txt", "r", encoding="utf-8-sig")
wordcount = Counter(file.read().split())
for item in wordcount.items():
print("{}\t-\t{}".format(*item))
输出应如下所示:
WORD FREQUENCY
can - 1
grow - 1
and - 1
shrink - 1
on - 1
demand - 1
TOTAL = 6
我的程序以不同的方式计算小写和大写。有没有办法过滤掉标点符号?
解决方案
创建单词列表时,通过str.lower将它们转换为小写
from collections import Counter
wordcount = Counter()
#Open the file
with open(r"sample_input.txt", "r", encoding="utf-8-sig") as file:
#Iterate through each line
for line in file:
#Strip any trailing or leading whitespaces
line = line.strip()
#Iterate over the words and keep updating counter
for word in line.split():
wordcount.update([word.lower()])
for key, value in wordcount.items():
print("{}\t-\t{}".format(key, value))
#Sum up the count of words
num_words = sum(wordcount.values())
print(num_words)
输出将是
can - 1
grow - 1
and - 1
shrink - 1
on - 1
demand - 1
6
推荐阅读
- c# - 将 BrokeredMessage 从 Postman 发送到 Azure 函数
- sql - 使用 TOP 和 ORDER BY 的查询非常慢
- java - 程序类型已经存在:org.bouncycastle.LICENSE
- c# - 依赖属性 - 从另一个属性继承?
- python-3.x - 使用 sparse_categorical_accuracy 和 label_encoded 数据在 TPU 上训练时出现维度错误
- javascript - 从父级传递给子级的道具并将这些道具设置为状态不会立即起作用
- c - 信号无法唤醒睡眠过程
- c# - 向使用 OpenXML 创建的电子表格文档中的单元格添加注释
- c - 没有这样的设备或地址是什么意思(错误代码6)
- javascript - 如何在没有用户输入的情况下从控制器触发 angucomplete-alt 的远程 API 处理程序?