python - 对出现字符串的计数,四种方法,第三种不知道怎么不行

查看:109
本文介绍了python - 对出现字符串的计数,四种方法,第三种不知道怎么不行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

import os
import json
os.chdir("F:\\pydata-book-master\\ch02")
path='usagov_bitly_data2012-03-16-1331923249.txt'
open(path).readline()
records=[json.loads(line) for line in open(path) ]
time_zones=[rec['tz'] for rec in records if 'tz' in rec]


# method1
def get_counts(sequence):
    counts={}
    for x in sequence:
        if x in counts:
            print(x)
            print(counts)
            counts[x]+=1
        else:
            counts[x]=1
    return counts

#######################################

# method2
from collections import defaultdict
def get_counts2(sequence):
    counts=defaultdict(int)
    for x in sequence:
        counts[x]+=1
    return counts
print(get_counts2(time_zones))
##########################################


# method3
from collections import defaultdict
def get_counts2(sequence):
    counts={}
    for x in sequence:
        counts[x]+=1
    return counts
print(get_counts2(time_zones))

##########################################

# method4
from collections import Counter
counts=Counter(time_zones)
print(counts)


# error of method3

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-7-cce65f8fc4d0> in <module>()
     40         counts[x]+=1
     41     return counts
---> 42 print(get_counts2(time_zones))
     43 
     44 ##########################################

<ipython-input-7-cce65f8fc4d0> in get_counts2(sequence)
     38     counts={}
     39     for x in sequence:
---> 40         counts[x]+=1
     41     return counts
     42 print(get_counts2(time_zones))

KeyError: 'America/New_York'



解决方案

method3中的用法, 触发了KeyError异常, 因为你在没有初始化值的情况下, 直接就counts[x]+=1, 这样它压根找到之前没定义过的key, 就更别说+1, 你只是import defaultdict, 却没用上, 导致实际上逻辑和method1一样, 所以,解决的方法,就是method1

这篇关于python - 对出现字符串的计数,四种方法,第三种不知道怎么不行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆