aboutsummaryrefslogtreecommitdiff
path: root/challenge-032/paulo-custodio/python/ch-1.py
diff options
context:
space:
mode:
authorConor Hoekstra <codereport@outlook.com>2021-12-24 22:16:15 -0500
committerConor Hoekstra <codereport@outlook.com>2021-12-24 22:16:15 -0500
commitc804b128cf740d95b244cd3fe15e86d0820ab51e (patch)
treeb9db7c3a5f93e6a83640f56bfd5decb9bbe8dbfe /challenge-032/paulo-custodio/python/ch-1.py
parent116add27d0d74360c7d4ad26b12d972657e51afa (diff)
parent6f518c687f743b68d3eeddedcf3d831aca20d4ec (diff)
downloadperlweeklychallenge-club-c804b128cf740d95b244cd3fe15e86d0820ab51e.tar.gz
perlweeklychallenge-club-c804b128cf740d95b244cd3fe15e86d0820ab51e.tar.bz2
perlweeklychallenge-club-c804b128cf740d95b244cd3fe15e86d0820ab51e.zip
Merge branch 'master' of https://github.com/manwar/perlweeklychallenge-club
Diffstat (limited to 'challenge-032/paulo-custodio/python/ch-1.py')
-rw-r--r--challenge-032/paulo-custodio/python/ch-1.py51
1 files changed, 51 insertions, 0 deletions
diff --git a/challenge-032/paulo-custodio/python/ch-1.py b/challenge-032/paulo-custodio/python/ch-1.py
new file mode 100644
index 0000000000..717d0f8ded
--- /dev/null
+++ b/challenge-032/paulo-custodio/python/ch-1.py
@@ -0,0 +1,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]}")