forked from spotify/luigi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordcount.py
80 lines (65 loc) · 2.87 KB
/
wordcount.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from luigi import six
import luigi
class InputText(luigi.ExternalTask):
"""
This class represents something that was created elsewhere by an external process,
so all we want to do is to implement the output method.
"""
date = luigi.DateParameter()
def output(self):
"""
Returns the target output for this task.
In this case, it expects a file to be present in the local file system.
:return: the target output for this task.
:rtype: object (:py:class:`luigi.target.Target`)
"""
return luigi.LocalTarget(self.date.strftime('/var/tmp/text/%Y-%m-%d.txt'))
class WordCount(luigi.Task):
date_interval = luigi.DateIntervalParameter()
def requires(self):
"""
This task's dependencies:
* :py:class:`~.InputText`
:return: list of object (:py:class:`luigi.task.Task`)
"""
return [InputText(date) for date in self.date_interval.dates()]
def output(self):
"""
Returns the target output for this task.
In this case, a successful execution of this task will create a file on the local filesystem.
:return: the target output for this task.
:rtype: object (:py:class:`luigi.target.Target`)
"""
return luigi.LocalTarget('/var/tmp/text-count/%s' % self.date_interval)
def run(self):
"""
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target
"""
count = {}
# NOTE: self.input() actually returns an element for the InputText.output() target
for f in self.input(): # The input() method is a wrapper around requires() that returns Target objects
for line in f.open('r'): # Target objects are a file system/format abstraction and this will return a file stream object
for word in line.strip().split():
count[word] = count.get(word, 0) + 1
# output data
f = self.output().open('w')
for word, count in six.iteritems(count):
f.write("%s\t%d\n" % (word, count))
f.close() # WARNING: file system operations are atomic therefore if you don't close the file you lose all data