• 【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

  • 相关阅读:
    ASP.NET MVC什么时候使用异步Action
    linux 下查看机器是cpu是几核的
    Linux--U盘安装Ubuntu12.04[转]
    再谈IE的浏览器模式和文档模式[转]
    Ubuntu 12.04.1 mysql从5.5升级到5.6
    在Linux上挂载Windows共享文件夹,如何开机自动挂载(mount)
    JConsole监控远程Tomcat服务器
    ubuntu iptables设置【转】
    oneinstack一键部署linux生产环境那点事(ubuntu)
    linux下jdk_tomcat+mysql配置那点事
  • 原文地址:https://www.cnblogs.com/OliverQin/p/7899228.html
Copyright © 2020-2023  润新知