【Python】分析文本split()

分析单个文本

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

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

运行结果如下:

image

现在存在一个文本如下:

image

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

file_path = "txtMyFavoriteFruit.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="txtMyFavoriteFruit.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 = ['txtA.txt','txtB.txt','txtC.txt']
for file_path in file_paths:
    count_words(file_path)

运行结果:

image

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