2013-04-24 5 views
0

제 질문은 이전 질문과 비슷합니다 : Python list help (incrementing count, appending). 내 대답을 잘 작동합니다. 그러나 이번에는 다른 질문이 있습니다.파이썬 카운터 키 값

json 파일에서 문자열을 구문 분석하고 정리 한 다음 새 문자열을 추가하십시오. 각 단어의 카운터를 가져와야합니다 (고유 한 목록으로 만들어지고 카운터가 업데이트됩니다), 높은 값에서 낮은 값으로 정렬합니다 (여기에서 most_common을 사용해야한다고 생각합니다). 그런 다음 목록을 20으로 제한합니다. 자바 스크립트에서는이 모든 작업을 수행하지만 파이썬에서는 수행하지 않습니다.

상세히, 나는 다시 for 루프를 통해 문자열 (json strings 파일)에서 각 문자열을 얻습니다.

# Counter for each word. 
words = Counter(); 

for e in strings: 
    # I am cleaning up the string here for unwanted chars, make it lower case 
    # and append it to a new string variable. 
    # if I were to print the new string variable it will look like this: 
    # hello test another test append hi hai hello hello 

# i know I need to call words.update 
# should I run a for loop in my new string variable for each word? 

어떻게 20까지 제한 할 수 있습니까? 어떤 제안이 큰 감사 것

word, count 
hello 3 
test 2 
another 1 
append 1 
hai 1 
hi 1 

: 내가 생성하고자하는 어떤

이 같은 것입니다.

words.update(some_list_of_words) 

당신은 너무 발전기 표현에 전달할 수 있습니다 : 당신이 단어의 목록이있는 경우

답변

2

, 당신은 .update() 방법을 사용하십시오

words.update(word.lower() for word in e.split()) 

문자열을 분할 할 e 공백에있는 별도의 단어로 변환 한 다음 각 단어를 소문자로하고이를 계산합니다.

.most_common()

이 매개 변수를, 최대 항목 수는 반환 :

words.most_common(20) 

데모 단어의 작은 세트, 상위 3 가장 일반적인 단어로 제한 :

>>> from collections import Counter 
>>> words = Counter('spam ham eggs baz foo bar baz spam ham eggs spam spam bacon eggs ham spam spam spam eggs ham'.split()) 
>>> words.most_common(3) 
[('spam', 7), ('ham', 4), ('eggs', 4)]