python - 理解字典计数器和重构python代码
问题描述
我正在自学 Python,我开始重构 Python 代码以学习新的高效编码方式。
我试图为 做一个理解词典word_dict
,但我没有找到办法。我有两个问题:
- 我试图
word_dict[word] += 1
在我的理解词典中添加使用word_dict[word]:=word_dict[word]+1
- 我想检查该元素是否已经在使用的理解字典(我正在创建)中
if word not in word_dict
并且它不起作用。
理解词典是:
word_dict = {word_dict[word] := 0 if word not in word_dict else word_dict[word] := word_dict[word] + 1 for word in text_split}
这是代码,它读取文本并计算其中的不同单词。如果您知道更好的方法,请告诉我。
text = "hello Hello, water! WATER:HELLO. water , HELLO"
# clean then text
text_cleaned = re.sub(r':|!|,|\.', " ", text)
# Output 'hello Hello water WATER HELLO water HELLO'
# creates list without spaces elements
text_split = [element for element in text_cleaned.split(' ') if element != '']
# Output ['hello', 'Hello', 'water', 'WATER', 'HELLO', 'water', 'HELLO']
word_dict = {}
for word in text_split:
if word not in word_dict:
word_dict[word] = 0
word_dict[word] += 1
word_dict
# Output {'hello': 1, 'Hello': 1, 'water': 2, 'WATER': 1, 'HELLO': 2}
解决方案
欢迎来到 Python。有库集合(https://docs.python.org/3/library/collections.html),其中有一个名为 Counter 的类。这似乎很可能适合您的代码。这是拿来的吗?
from collections import Counter
...
word_dict = Counter(text_split)
推荐阅读
- python - Python PLY Parser - 将矩阵解析为列表列表
- python - QApplication 模块的 PyQt5 问题
- asp.net-core - 实体框架核心 2.1。使用大量子对象更新对象的正确方法
- c++ - C++:矩阵的运算符重载
- excel - Nesting ParamArrays when declaring Excel VBA functions like SUMIFS?
- flutter - 检查约束并相应地返回正文
- android - 实时数据在更改片段时再次赋予旧值
- html - 如何将 Ionic 日期时间选择器定位到屏幕顶部?
- html - 缩放转换时列中的 CSS 元素位于上边框下方
- python - How can i remove double quotes in cmd title