首页 > 解决方案 > 理解字典计数器和重构python代码

问题描述

我正在自学 Python,我开始重构 Python 代码以学习新的高效编码方式。

我试图为 做一个理解词典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}

标签: pythonrefactoringcounterdictionary-comprehension

解决方案


欢迎来到 Python。有库集合(https://docs.python.org/3/library/collections.html),其中有一个名为 Counter 的类。这似乎很可能适合您的代码。这是拿来的吗?

from collections import Counter
...
word_dict = Counter(text_split)

推荐阅读