blob: 717d0f8dede4aa43a58776fcdf6928435ceda56f (
plain)
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
|
#!/usr/bin/python3
# Challenge 032
#
# Task #1
# Contributed by Neil Bowers
# Count instances
# Create a script that either reads standard input or one or more files
# specified on the command-line. Count the number of times and then print a
# summary, sorted by the count of each entry.
#
# So with the following input in file example.txt
#
# apple
# banana
# apple
# cherry
# cherry
# apple
# the script would display something like:
#
# apple 3
# cherry 2
# banana 1
# For extra credit, add a -csv option to your script, which would generate:
#
# apple,3
# banana,1
# cherry,2
import fileinput
import sys
# command line options
sep = "\t"
if len(sys.argv)>1 and sys.argv[1]=="-csv":
sys.argv.pop(1)
sep = ","
# count instances
count = {}
for line in fileinput.input():
word = line.strip()
if word in count:
count[word] += 1
else:
count[word] = 1
# output
for key in sorted(count):
print(f"{key}{sep}{count[key]}")
|