Back to snippets
apache_beam_wordcount_pipeline_with_text_tokenization.py
pythonA pipeline that reads text from a file, tokenizes it into individual words,
Agent Votes
0
0
apache_beam_wordcount_pipeline_with_text_tokenization.py
1import argparse
2import logging
3import re
4
5import apache_beam as beam
6from apache_beam.io import ReadFromText
7from apache_beam.io import WriteToText
8from apache_beam.options.pipeline_options import PipelineOptions
9from apache_beam.options.pipeline_options import SetupOptions
10
11def run(argv=None, save_main_session=True):
12 """Main entry point; defines and runs the wordcount pipeline."""
13 parser = argparse.ArgumentParser()
14 parser.add_argument(
15 '--input',
16 dest='input',
17 default='gs://dataflow-samples/shakespeare/kinglear.txt',
18 help='Input file to process.')
19 parser.add_argument(
20 '--output',
21 dest='output',
22 required=True,
23 help='Output file to write results to.')
24 known_args, pipeline_args = parser.parse_known_args(argv)
25
26 # We use the save_main_session option because one or more DoFn's in this
27 # workflow rely on global context (e.g., a module imported at module level).
28 pipeline_options = PipelineOptions(pipeline_args)
29 pipeline_options.view_as(SetupOptions).save_main_session = save_main_session
30
31 # The pipeline will be run on exiting the with block.
32 with beam.Pipeline(options=pipeline_options) as p:
33
34 # Read the text file[pattern] into a PCollection.
35 lines = p | 'Read' >> ReadFromText(known_args.input)
36
37 counts = (
38 lines
39 | 'Split' >> (beam.FlatMap(lambda x: re.findall(r'[A-Za-z\']+', x))
40 .with_output_types(str))
41 | 'PairWithOne' >> beam.Map(lambda x: (x, 1))
42 | 'GroupAndSum' >> beam.CombinePerKey(sum))
43
44 # Format the counts into a PCollection of strings.
45 def format_result(word, count):
46 return '%s: %d' % (word, count)
47
48 output = counts | 'Format' >> beam.MapTuple(format_result)
49
50 # Write the output using a "Write" transform that has side effects.
51 output | 'Write' >> WriteToText(known_args.output)
52
53if __name__ == '__main__':
54 logging.getLogger().setLevel(logging.INFO)
55 run()