Repository navigation
Expand file tree
/
Copy pathget_langs.py
More file actions
executable file
·55 lines (42 loc) · 1.76 KB
/
Copy pathget_langs.py
File metadata and controls
executable file
·55 lines (42 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
"""
script to determine what programming languages students came to this class with
"""
infilename = "students.txt"
# all_langs = set() # use a set to ensure unique values
# with open(infilename) as f: # default read text mode
# f.readline() # read and toss the header
# # loop through the rest of the lines in the file
# for line in f:
# langs = line.split(':')[1] # toss the names
# # a bit of cleanup:
# langs = langs.replace(',', ' ')
# langs = langs.replace('and', ' ')
# langs = langs.split() # separate the languages
# for lang in langs:
# lang = lang.strip().capitalize() # clean them up -- and make case the same
# if lang: # don't want empty strings
# all_langs.add(lang)
# # done reading the file -- no on to the rest
# for lang in all_langs:
# print(lang)
# extra credit version: using collections.Counter:
# https://docs.python.org/3/library/collections.html#collections.Counter
from collections import Counter
all_langs = Counter()
with open(infilename) as f:
f.readline() # read and toss the header
for line in f:
langs = line.partition(':')[2] # get just what's after the colon
# a bit of cleanup:
langs = langs.replace(',', ' ').replace('and', ' ')
langs = langs.split() # separate the languages
for lang in langs:
if lang[0].isupper(): # there are some names in there!
continue
lang = lang.strip().capitalize() # clean them up -- and make case the same
if lang: # don't want empty strings
all_langs[lang] += 1
print("And now the counted version")
for lang, count in all_langs.items():
print(lang, ":", count)