Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Python counts the number of words in the text and two ways of writing print

Shulou Source: shulou.com Published: 2022-06-03 05:51:21 09月10日 Update

#! / usr/bin/python#-*-coding: utf-8-*-# function, counting the number of words in each text separately, and outputting the total number of words in all text a = [] sum = 0def count_words (filename): # filename = '1.txt' try: with open (filename) as file_object: t = file_object.read () except IOError: print' you have' +'+ filename +'is not words Else: words = t.split () numbers = len (words) a.append (numbers) # print can be written with a comma followed directly by the parameter value. It can also be written without a comma, followed by the% parameter value print 'danci de geshi yigong shi% d'% numbers# # print' danci de geshi yigong shi', numbersfilenames = ['1.txtcounting, numbersfilenames = [1.txtcounting, 2.txtrecording, 3.txt'] for filename in filenames: count_words (filename) for i in a: sum + = int (I) print sum#, one is counted in sum, the other is in sum function, and the parameter of # sum is a list. Here an is list#print 'the total number of all words is' + str (sum (a))

Tags: Words parameters writing text totals commas actions functions that is utf-8 output statistics Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Tech Info Shulou Technology MariaDB vpn