python-3.x - 如何计算键中值的出现次数?
问题描述
我已经检查了解决方案,字典:如何计算列表中值的频率 - Python3、stackoverflow 以及 google 中的其他选项。而不是从键中获取出现次数。我从单词中收到了字符的数量,但实际上没有收到单词的数量。
import csv
from collections import defaultdict
content = "Note.csv"
collector = {}
with open(content, 'r') as file:
genres = csv.DictReader(file, skipinitialspace=True)
for row in genres:
collector = {"Genre": f'{row["others"]}',
"Title": f'{row["title"]}'}
print(collector)
colors = ['r','g']
for k, v in collector.items():
D = defaultdict(list)
for i, item in enumerate(v):
D[item].append(i)
D = {k: v for k, v in D.items()}
print(k, D)
Note.csv 包含以下内容:
title, author, year, others, note
Everything,Nobody,2222,Fiction,This is just something of everything!
Nothing,Everybody,1111,Romance,This is nothing of anything!
Pokemon,Pikachu,1999,Fiction,Once upon time.
最终结果实际上应该是这样的。1:浪漫;2:小说
根据结果,我希望能够创建一个饼图。
与往常一样,非常感谢您提供有用的意见和回答!
此致,
解决方案
如果您只是计算每种类型的数量,您可以使用 a Counter
:
from collections import Counter
with open(content, 'r') as file:
genres = csv.DictReader(file, skipinitialspace=True)
c = Counter(row["others"] for row in genres)
print(c)
# Counter({'Fiction': 2, 'Romance': 1})
推荐阅读
- javascript - 获得 Microsoft 365 订阅价格时使用什么 api(即 Office 365 Business Essentials - 6 美元/每位用户每月)
- python - 图像不会在整个框架 wx.python 上展开
- c# - 在运行时根据字符串编辑代码
- string - 恰好有 1 个三元组 b 的所有字符串的语言
- html - 如何使用 xpath 获取所有 h2 元素的下一个元素的文本?
- ios - 尽管项目包含配置文件并且已上传到机器人服务器,但机器人无法找到配置文件
- python - Python多处理 - 仅返回部分值而不是整个值
- javascript - 如果选项名称在不同的 optgroup 下相同,如何从选择框中选择“选项”名称
- java - android base64在php中编码和解码
- xamarin.forms - 如何使用意图过滤器将 gmail 附件放入本地设备商店