我已经实现了以下代码,它可以完美运行,没有任何问题。但是我不满意,因为它看起来不漂亮?最重要的是,我觉得它看起来不像 pythonic 的方式。
所以我想我会听取stackoverflow社区的建议。此方法从 sql 查询中获取其数据,该查询在另一种方法中返回字典并基于该字典中的数据,我正在执行模式匹配和计数过程。我想以 Pythonic 的方式执行此操作并返回更好的数据结构。
这是代码:
def getLaguageUserCount(self):
bots = self.getBotUsers()
user_template_dic = self.getEnglishTemplateUsers()
print user_template_dic
user_by_language = {}
en1Users = []
en2Users = []
en3Users=[]
en3Users=[]
en4Users=[]
en5Users=[]
en_N_Users=[]
en1 = 0
en2 = 0
en3 = 0
en4 = 0
en5 = 0
enN = 0
lang_regx = re.compile(r'User_en-([1-5n])', re.M|re.I)
for userId, langCode in user_template_dic.iteritems():
if userId not in bots:
print 'printing key value'
for item in langCode:
item = item.replace('--','-')
match_lang_obj = lang_regx.match(item)
if match_lang_obj is not None:
if match_lang_obj.group(1) == '1':
en1 += 1
en1Users.append(userId)
if match_lang_obj.group(1) == '2':
en2 += 1
en2Users.append(userId)
if match_lang_obj.group(1) == '3':
en3 += 1
en3Users.append(userId)
if match_lang_obj.group(1) == '4':
en4 += 1
en4Users.append(userId)
if match_lang_obj.group(1) == '5':
en5 += 1
en5Users.append(userId)
if match_lang_obj.group(1) == 'N':
enN += 1
en_N_Users.append(userId)
else:
print "Group didn't match our regex: " + item
else:
print userId + ' is a bot'
language_count = {}
user_by_language['en-1-users'] = en1Users
user_by_language['en-2-users'] = en2Users
user_by_language['en-3-users'] = en3Users
user_by_language['en-4-users'] = en4Users
user_by_language['en-5-users'] = en5Users
user_by_language['en-N-users'] = en_N_Users
user_by_language['en-1'] = en1
user_by_language['en-2'] = en2
user_by_language['en-3'] = en3
user_by_language['en-4'] = en4
user_by_language['en-5'] = en5
user_by_language['en-n'] = enN
return user_by_language