理解字典计数器和重构python代码
我正在自学Python,我开始重构Python代码,学习新的高效的编码方法 我试着为单词词典做一个理解词典,但是我没有找到一个方法。我有两个问题:理解字典计数器和重构python代码,python,refactoring,counter,dictionary-comprehension,Python,Refactoring,Counter,Dictionary Comprehension,我正在自学Python,我开始重构Python代码,学习新的高效的编码方法 我试着为单词词典做一个理解词典,但是我没有找到一个方法。我有两个问题: 我试着用word-dict[word]:=word-dict[word]+1在我的理解词典中添加word-dict[word]+=1 我想用检查元素是否已经在理解词典(我正在创建)中,如果单词不在word\u dict中,那么它就不起作用了 理解词典是: word\u dict={word\u dict[word]:=0如果单词不在word中,则
- 我试着用
word-dict[word]:=word-dict[word]+1在我的理解词典中添加
word-dict[word]+=1
- 我想用
检查元素是否已经在理解词典(我正在创建)中,如果单词不在word\u dict中,那么它就不起作用了
word\u dict={word\u dict[word]:=0如果单词不在word中,则为word\u dict[word]:=word\u dict[word]+1表示文本中的单词\u 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。还有库集合(),它有一个名为Counter的类。这很可能适合您的代码。这是一个拍摄吗
from collections import Counter
...
word_dict = Counter(text_split)
现在,您正在使用正则表达式删除一些不需要的字符,然后在空格上拆分以获得单词列表。为什么不使用正则表达式立即获取单词?您还可以利用集合计数器创建字典,其中键为单词,关联值为计数/出现次数:
import re
from collections import Counter
text = "hello Hello, water! WATER:HELLO. water , HELLO"
pattern = r"\b\w+\b"
print(Counter(re.findall(pattern, text)))
输出:
Counter({'water': 2, 'HELLO': 2, 'hello': 1, 'Hello': 1, 'WATER': 1})
>>>
下面是正则表达式模式的组成部分:
-表示单词边界(将不包括在匹配中)\b
-集合中的一个或多个字符\w+
[a-zA-Z0-9\
-另一个单词边界(也不包括在匹配中)\b