1. 程式人生 > >【Python】分析文本split()

【Python】分析文本split()

display msg round exc 修改 com 分享圖片 pla nts

分析單個文本

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()