github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/examples/wordcount.py (about) 1 # 2 # Licensed to the Apache Software Foundation (ASF) under one or more 3 # contributor license agreements. See the NOTICE file distributed with 4 # this work for additional information regarding copyright ownership. 5 # The ASF licenses this file to You under the Apache License, Version 2.0 6 # (the "License"); you may not use this file except in compliance with 7 # the License. You may obtain a copy of the License at 8 # 9 # http://www.apache.org/licenses/LICENSE-2.0 10 # 11 # Unless required by applicable law or agreed to in writing, software 12 # distributed under the License is distributed on an "AS IS" BASIS, 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 # See the License for the specific language governing permissions and 15 # limitations under the License. 16 # 17 18 """A word-counting workflow.""" 19 20 # pytype: skip-file 21 22 # beam-playground: 23 # name: WordCount 24 # description: An example that counts words in Shakespeare's works. 25 # multifile: false 26 # pipeline_options: --output output.txt 27 # context_line: 44 28 # categories: 29 # - Combiners 30 # - Options 31 # - Quickstart 32 # complexity: MEDIUM 33 # tags: 34 # - options 35 # - count 36 # - combine 37 # - strings 38 39 import argparse 40 import logging 41 import re 42 43 import apache_beam as beam 44 from apache_beam.io import ReadFromText 45 from apache_beam.io import WriteToText 46 from apache_beam.options.pipeline_options import PipelineOptions 47 from apache_beam.options.pipeline_options import SetupOptions 48 49 50 class WordExtractingDoFn(beam.DoFn): 51 """Parse each line of input text into words.""" 52 def process(self, element): 53 """Returns an iterator over the words of this element. 54 55 The element is a line of text. If the line is blank, note that, too. 56 57 Args: 58 element: the element being processed 59 60 Returns: 61 The processed element. 62 """ 63 return re.findall(r'[\w\']+', element, re.UNICODE) 64 65 66 def run(argv=None, save_main_session=True): 67 """Main entry point; defines and runs the wordcount pipeline.""" 68 parser = argparse.ArgumentParser() 69 parser.add_argument( 70 '--input', 71 dest='input', 72 default='gs://dataflow-samples/shakespeare/kinglear.txt', 73 help='Input file to process.') 74 parser.add_argument( 75 '--output', 76 dest='output', 77 required=True, 78 help='Output file to write results to.') 79 known_args, pipeline_args = parser.parse_known_args(argv) 80 81 # We use the save_main_session option because one or more DoFn's in this 82 # workflow rely on global context (e.g., a module imported at module level). 83 pipeline_options = PipelineOptions(pipeline_args) 84 pipeline_options.view_as(SetupOptions).save_main_session = save_main_session 85 86 # The pipeline will be run on exiting the with block. 87 with beam.Pipeline(options=pipeline_options) as p: 88 89 # Read the text file[pattern] into a PCollection. 90 lines = p | 'Read' >> ReadFromText(known_args.input) 91 92 counts = ( 93 lines 94 | 'Split' >> (beam.ParDo(WordExtractingDoFn()).with_output_types(str)) 95 | 'PairWithOne' >> beam.Map(lambda x: (x, 1)) 96 | 'GroupAndSum' >> beam.CombinePerKey(sum)) 97 98 # Format the counts into a PCollection of strings. 99 def format_result(word, count): 100 return '%s: %d' % (word, count) 101 102 output = counts | 'Format' >> beam.MapTuple(format_result) 103 104 # Write the output using a "Write" transform that has side effects. 105 # pylint: disable=expression-not-assigned 106 output | 'Write' >> WriteToText(known_args.output) 107 108 109 if __name__ == '__main__': 110 logging.getLogger().setLevel(logging.INFO) 111 run()