Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative Frequency in Python

Tags:

python

Is it possible to calculate the relative frequency of elements occurring in a list in Python?

For example:

['apple', 'banana', 'apple', 'orange'] # apple for example would be 0.5
like image 901
Alpine Avatar asked Mar 21 '15 03:03

Alpine


1 Answers

You can use NLTK for this:

import ntlk
text = ['apple', 'banana', 'apple', 'orange']
fd = nltk.FreqDist(text)

Check out the tutorial in the book the how to and the source code

Alternately, you could use a Counter:

from collections import Counter
text = ['apple', 'banana', 'apple', 'orange']
c = Counter(text)
like image 150
craighagerman Avatar answered Sep 22 '22 15:09

craighagerman