Skip to content

Commit 9e813bd

Browse files
committed
PR6
1 parent cdcc055 commit 9e813bd

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

11/generators-atakume.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
Turn the following unix pipeline into Python code using generators
3+
4+
$ for i in ../*/*py; do grep ^import $i|sed 's/import //g' ; done | sort | uniq -c | sort -nr
5+
4 unittest
6+
4 sys
7+
3 re
8+
3 csv
9+
2 tweepy
10+
2 random
11+
2 os
12+
2 json
13+
2 itertools
14+
1 time
15+
1 datetime
16+
"""
17+
import glob
18+
import re
19+
from collections import Counter
20+
21+
22+
def gen_files(pat):
23+
yield from glob.glob(pat)
24+
25+
26+
def gen_lines(files):
27+
for filepath in files:
28+
with open(filepath, 'r') as file:
29+
yield from file.readlines()
30+
31+
32+
def gen_grep(lines, pattern):
33+
regex = re.compile(pattern)
34+
for line in lines:
35+
if regex.match(line):
36+
yield regex.sub("", line).strip()
37+
38+
39+
def gen_count(lines):
40+
yield from sorted(Counter(lines).items(), key=lambda pair: (pair[1], pair[0]), reverse=True)
41+
42+
if __name__ == "__main__":
43+
# call the generators, passing one to the other
44+
files = gen_files('../*/*.py')
45+
lines = gen_lines(files)
46+
imports = gen_grep(lines, "^import")
47+
counts = gen_count(imports)
48+
for k, v in counts:
49+
print(v, k)

0 commit comments

Comments
 (0)