标签:play list 9.png one out obj 存在 content images
split()方法,是以空格为分隔符将字符串拆分成多个部分,并将这些部分存储到一个列表中
title = ‘My name is oliver!‘ list = title.split() print(list)
运行结果如下:
现在存在一个文本如下:
我们要统计这个文本中有多少个字符
file_path = "txt\MyFavoriteFruit.txt" try: with open(file_path) as file_object: contents = file_object.read() except FileNotFoundError: msg = "Sorry,the file does not exist." print(msg) else: #计算该文件包含多少个单词 words = contents.split() num_words = len(words) print("The file "+" has about " + str(num_words) +" words.")
上面只是对单个文本进行分析,那么我们对多个文本进行分析时,不可能每次都去修改file_path,所以在这里我们使用函数来进行分析
def count_words(file_path): try: with open(file_path) as file_object: contents = file_object.read() except FileNotFoundError: msg = "Sorry,the file does not exist." print(msg) else: #计算该文件包含多少个单词 words = contents.split() num_words = len(words) print("The file "+" has about " + str(num_words) +" words.") #调用函数 file_path="txt\MyFavoriteFruit.txt" count_words(file_path)
加入现在想对A.txt,B.txt,C.txt三个文件同时统计文件字数,那么只需要循环调用即可
def count_words(file_path): try: with open(file_path) as file_object: contents = file_object.read() except FileNotFoundError: msg = "Sorry,the file does not exist." print(msg) else: #计算该文件包含多少个单词 words = contents.split() num_words = len(words) print("The file "+" has about " + str(num_words) +" words.") #调用函数 file_paths = [‘txt\A.txt‘,‘txt\B.txt‘,‘txt\C.txt‘] for file_path in file_paths: count_words(file_path)
运行结果:
标签:play list 9.png one out obj 存在 content images
原文地址:http://www.cnblogs.com/OliverQin/p/7899228.html