forked from polytech-nantes-puddi/tp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpart2-wordcount-hamlet-pyspark.py
More file actions
39 lines (28 loc) · 1.09 KB
/
Copy pathpart2-wordcount-hamlet-pyspark.py
File metadata and controls
39 lines (28 loc) · 1.09 KB
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
import re
import sys
import time
from pyspark.sql import SparkSession
debug = "--debug" in sys.argv or "-d" in sys.argv
cache = "--cache" in sys.argv or "-c" in sys.argv
pattern = re.compile("^[mM][a-z]+$")
spark = SparkSession.builder.master(
'local[*]').appName('BigDataTP').getOrCreate()
sc = spark.sparkContext
sc.setLogLevel("WARN")
print("Start")
start_time = time.time()
text_file = sc.textFile("dataset/wordcount/hamlet.txt")
print(text_file.collect()) if debug else None
words = text_file.flatMap(lambda line: line.split(" "))
print(words.collect()) if debug else None
words_filtered = words.map(lambda x: x.lower()).filter(
lambda x: pattern.match(x))
print(words_filtered.collect()) if debug else None
wordCounts = words_filtered.map(lambda word: (
word, 1)).reduceByKey(lambda a, b: a + b)
print(wordCounts.collect()) if debug else None
wordCounts.saveAsTextFile("output/wordcount/") if cache else None
wordCounts_sorted = wordCounts.sortBy(lambda a: a[1], ascending=False).take(10)
print(wordCounts_sorted)
print("End")
print("--- %s seconds ---" % (time.time() - start_time))