码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】分析文本split()

时间:2017-11-26 16:46:36      阅读:194      评论:0      收藏:0      [点我收藏+]

标签: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)

运行结果:

技术分享图片

【Python】分析文本split()

标签:play   list   9.png   one   out   obj   存在   content   images   

原文地址:http://www.cnblogs.com/OliverQin/p/7899228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!