【Python】分析文本split()

分析单个文本

split()方法,是以空格为分隔符将字符串拆分成多个部分,并将这些部分存储到一个列表中

title = 'My name is oliver!'
list = title.split()
print(list)

运行结果如下:

image

现在存在一个文本如下:

image

我们要统计这个文本中有多少个字符

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)

运行结果:

image

转载于:https://www.cnblogs.com/OliverQin/p/7899228.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值