標籤:分享 length mes bubuko http counter inf 數組 append
方法一:
推導式
dd="ewq4aewtaSDDSFDTFDSWQrtewtyufashas" print {i:dd.count(i) for i in dd}
方法二:
counter
import collectionsdd="ewq4aewtaSDDSFDTFDSWQrtewtyufashas"obj = collections.Counter(dd)print obj
方法三:
和方法一類似
dd="ewq4aewtaSDDSFDTFDSWQrtewtyufashas"for i in set(dd): print(i,dd.count(i))
方法四:
dd = ‘ewq4aewtaSDDSFDTFDSWQrtewtyufashas‘ d = {} for c in dd: d[c] = (d[c] + 1) if (c in d) else (1) print d
列印出排行前三的字元
dd="ewq4aewtaSDDSFDTFDSWQrtewtyufashas"obj = collections.Counter(dd)print obj.most_common(3)
python統計一個文檔中 各個字元出現的次數
f = file("data.txt")s = f.read()# 這裡的s採用檔案的方式讀取global list_allglobal list_to_statisticdef tran_s_to_list(s):list_all = []l = len(s)# 得到長度,遍曆for x in xrange(0,l):# 當x不在list中,即第一次出現,追加到list中if not s[x] in list_all:list_all.append(s[x])return list_alldef statistic(s, list_all, list_to_statistic):l = len(s)for x in xrange(0,l):遍曆字串,找到每一個char在list中的index,在list_statistic相應位置加一list_to_statistic[list_all.index(s[x])] = list_to_statistic[list_all.index(s[x])]+1# print list_all.index(s[x]),# printlist_all = tran_s_to_list(s)# 複製一個和list等長的數組list_statistic,並且全部賦值為0list_to_statistic = list_all[ : ]for x in xrange( 0, len(list_all) ):list_to_statistic[x] = 0statistic(s, list_all, list_to_statistic);# 列印listlength = len(list_all)for x in xrange(0, listlength):print str(list_all[x])+"" + "---appers---"+str(list_to_statistic[x])+"---times"
python統計字串裡每個字元的次數