【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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM