Skip to content
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
1 change: 1 addition & 0 deletions bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def run1(args, src_name, num_runs):
runs = [
[['java', '-jar', './bin/freq01scala.jar'], 'freq01.scala', 3],
[['python', './src/freq01.py'], 'freq01.py', 3],
[['python', './src/freq02.py'], 'freq02.py', 3],
[['./bin/freq03cpp' + EXE], 'freq03.cpp'],
[['./bin/freq02cpp' + EXE], 'freq02.cpp'],
[['./bin/freq01cpp' + EXE], 'freq01.cpp'],
Expand Down
46 changes: 46 additions & 0 deletions src/freq02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import string
import sys
from collections import Counter

from itertools import chain


if len(sys.argv) != 3:
print('No args')
exit(1)


def sort_key(x):
word, fq = x
return -fq, word


non_alpha = bytes(ch for ch in range(256) if chr(ch) not in string.ascii_letters)


tab = bytes.maketrans(
string.ascii_uppercase.encode() + non_alpha,
string.ascii_lowercase.encode() + b' ' * len(non_alpha)
)


with open(sys.argv[1], 'rb') as in_file:
# Replace any non-alphabetical symbols with spaces and split the string using space separator.
translated = chain.from_iterable(
line.translate(tab).split(b' ') for line in in_file
)

# Ignore empty strings.
words = filter(None, translated)

counts = sorted(Counter(words).items(), key=sort_key)

result = b'\r\n'.join(
b' '.join(
(str(v).encode(), k)
)
for k, v in counts
) + b'\r\n'

with open(sys.argv[2], 'wb+') as out_file:
out_file.write(result)