Last active
December 11, 2019 20:18
-
-
Save mpkocher/cf5639f5fca3675b00ab5af7225c146c to your computer and use it in GitHub Desktop.
Example of using collections.Counter https://twitter.com/DavidMezzetti/status/1204493772274438151
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
from collections import Counter | |
# https://docs.python.org/3.8/library/collections.html?highlight=counter#collections.Counter | |
# Example of using collections.Counter to count item | |
# https://twitter.com/DavidMezzetti/status/1204493772274438151 | |
def reader(file_name): | |
# don't read the entire file into memory | |
with open(file_name) as f: | |
for line in f: | |
for x in line.strip().split(" "): | |
if x: | |
yield x | |
def run(file_name, max_results=3): | |
c = Counter(reader(file_name)) | |
results = [k for k, _ in c.most_common(max_results)] | |
print(results) | |
return 0 | |
if __name__ == '__main__': | |
sys.exit(run(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment