Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Optimize bash and python #75

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bash/wordcount.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env bash
export LC_COLLATE=C
sed 's/[\t ]/\n/g' | grep -v ^$ | sort | uniq -c | sed 's/^\s*//' | sort -k1,2nr -k2 | awk 'BEGIN{OFS="\t"}{print $2,$1}'
export PHYS_CORES=$(cat /proc/cpuinfo | grep 'core id' | sort | uniq | wc -l)
sed -E 's/[\t ]+/\n/g' | grep -v ^$ | sort -S 40% --parallel $PHYS_CORES | uniq -c | sort -S 40% ---parallel $PHYS_CORES 2 -k1,2nr -k2 | awk 'BEGIN{OFS="\t"}{print $2,$1}'
28 changes: 20 additions & 8 deletions python/wordcount_py3.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,30 @@
#!/usr/bin/env python3
from collections import defaultdict
from itertools import groupby
from sys import stdin
import codecs

stdin = codecs.getreader('utf8')(stdin.detach(), errors='ignore')

from sys import stdout

def word_count():
counter = defaultdict(int)
for l in stdin:
for word in bytes(l, 'utf8').split():
for l in stdin.buffer:
for word in l.split():
counter[word] += 1
for word, cnt in sorted(counter.items(), key=lambda x: (-x[1], x[0])):
print('{0}\t{1}'.format(word.decode('utf8'), cnt))

groupedcounts = defaultdict(list)
for word, count in counter.items():
groupedcounts[count].append(word)
del counter

grouped_list = list(groupedcounts.items())
del groupedcounts
grouped_list.sort(key=lambda x: -x[0])

for count, words in grouped_list:
suffix = b'\t' + str(count).encode('utf-8') + b'\n'
words.sort()
for word in words:
stdout.buffer.write(word)
stdout.buffer.write(suffix)

if __name__ == '__main__':
word_count()