저는 긴 문자열을 구문 분석하고 각 단어가 파이썬에서 발생하는 횟수를 계산합니다. 나는 작동하는 함수를 가지고 있지만, 속도면에서 더 효율적으로 만들 수있는 방법이 있는지, 그리고 내가 이것을 할 수있는 파이썬 라이브러리 함수가있을 지에 대한 조언을 찾고있다. 그래서 나는 바퀴를 재발 명하지 않는다. ?문자열의 단어 빈도를 효율적으로 계산하십시오.
긴 문자열 (일반적으로 문자열의 1000 단어 이상)에서 발생하는 가장 일반적인 단어를 계산하는보다 효율적인 방법을 제안 할 수 있습니까?
1 요소는 가장 일반적인 단어 목록에 사전을 정렬하는 가장 좋은 방법, 두 번째 요소는 2 번째로 가장 일반적인 단어 등이다 또한 뭐죠?
test = """abc def-ghi jkl abc
abc"""
def calculate_word_frequency(s):
# Post: return a list of words ordered from the most
# frequent to the least frequent
words = s.split()
freq = {}
for word in words:
if freq.has_key(word):
freq[word] += 1
else:
freq[word] = 1
return sort(freq)
def sort(d):
# Post: sort dictionary d into list of words ordered
# from highest freq to lowest freq
# eg: For {"the": 3, "a": 9, "abc": 2} should be
# sorted into the following list ["a","the","abc"]
#I have never used lambda's so I'm not sure this is correct
return d.sort(cmp = lambda x,y: cmp(d[x],d[y]))
print calculate_word_frequency(test)
'has_key'이되지 않습니다. 대신'key in d'를 사용하십시오. 또한, 정렬 함수는 꽤 잘못되었습니다. 'return sorted (d, key = d .__ getitem__, reverse = True)'는 빈도별로 내림차순 정렬을 수행하고 키를 반환합니다. – agf