development

파이썬에서 사전의 키워드 수 계산

big-blog 2020. 5. 6. 21:55
반응형

파이썬에서 사전의 키워드 수 계산


값 = 키워드 반복이있는 사전에 단어 목록이 있지만 고유 단어 목록 만 원하므로 키워드 수를 세고 싶었습니다. 키워드 수를 세는 방법이 있거나 다른 단어를 찾아야하는 다른 방법이 있습니까?


len(yourdict.keys())

아니면 그냥

len(yourdict)

파일에서 고유 한 단어를 세고 싶다면 사용 set하고 좋아할 수 있습니다.

len(set(open(yourdictfile).read().split()))

고유 한 단어 수 (즉, 사전의 항목 수)는 len()함수를 사용하여 찾을 수 있습니다 .

> a = {'foo':42, 'bar':69}
> len(a)
2

구별되는 단어 (예 : 키)를 모두 얻으려면이 .keys()방법을 사용하십시오 .

> list(a.keys())
['foo', 'bar']

질문이 키워드 수를 세는 것에 관한 것이라면 다음과 같은 것이 좋습니다.

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

주 함수에는 데이터를 반복하고 값을 countoccurrences 함수에 전달하는 무언가가 있습니다.

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

코드 출력

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

len()사전에서 직접 호출 하면 반복자를 작성 d.keys()하고 호출 하는 것보다 빠르지 만 len()프로그램의 다른 작업과 비교할 때 속도는 무시할 수 있습니다.

d = {x: x**2 for x in range(1000)}

len(d)
# 1000

len(d.keys())
# 1000

%timeit len(d)
# 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit len(d.keys())
# 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

참고 URL : https://stackoverflow.com/questions/2212433/counting-the-number-of-keywords-in-a-dictionary-in-python

반응형