• 学习心得2020.08.09


    027集合

    对集合赋值时,重复的数,只会在集合中出现一次

    >>> num2={1,2,3,4,5,5,4,3,2}
    >>> num2
    {1, 2, 3, 4, 5}
    

    如何创建一个集合

    +一种是直接把一堆元素用花括号括起来
    +一种是使用set()工厂函数

    >>> set1=set([1,2,3,4,5,5])
    >>> set1
    {1, 2, 3, 4, 5}
    

    如何访问集合中的值

    +可以使用for把集合中的数据一个个读取出来
    +可以通过in和not in判断一个元素是否在集合中已经存在

    >>> 1 in num2
    True
    >>> '1' in num2
    False
    

    不可变集合frozenset()

    >>> num3=frozenset([1,2,3,4,5])
    >>> num3.add(0)
    Traceback (most recent call last):
      File "<pyshell#19>", line 1, in <module>
        num3.add(0)
    AttributeError: 'frozenset' object has no attribute 'add'
    

    028文件

    文件打开模式

    文件对象方法


    +打开一个现有的文件(可读)

    >>> f=open('D:\那些要用的软件\python\program\record.txt')
    >>> f
    <_io.TextIOWrapper name='D:\那些要用的软件\python\program\record.txt' mode='r' encoding='cp936'>
    

    +新建一个可写的文件

    >>> f=open('D:\那些要用的软件\python\program\test.txt','w')
    >>> f.write('我爱鱼C工作室')
    7
    >>> f.close()
    

    029文件:一个任务

    将文件(record.txt)中的数据进行分割并按照以下规律保存起来:
    +小甲鱼的对话单独保存为boy_.txt的文件(去掉“小甲鱼:”)
    +小客服的对话单独保存为girl_
    .txt的文件(去掉“小客服:”)
    +文件中总共有三段对话,分别保存为boy_1.txt,girl_1.txt,boy_2.txt,girl_2.txt,boy_3.txt,girl_3.txt共6个文件(提示:文件中不同的对话间已经使用“==========”分割)

    def save_file(boy,girl,count):
        file_name_boy='boy_'+str(count)+'.txt'
        file_name_girl='girl_'+str(count)+'.txt'
    
        boy_file=open(file_name_boy,'w')
        girl_file=open(file_name_girl,'w')
    
        boy_file.writelines(boy)
        girl_file.writelines(girl)
    
        boy_file.close()
        girl_file.close()
    
    def split_file(file_name):
        f=open('D:\那些要用的软件\python\program\record.txt')
    
        boy=[]
        girl=[]
        count=1
    
        for each_line in f:
            if each_line[:6]!='======':
                (role,line_spoken)=each_line.split(":",1)
                if role =='小甲鱼':
                    boy.append(line_spoken)
                if role =='小客服':
                    girl.append(line_spoken)
            else:
                save_file(boy,girl,count)
    
                boy=[]
                girl=[]
                count+=1
    
        save_file(boy,girl,count)
                
        f.close()
    split_file('record.txt')
    
  • 相关阅读:
    加速你的Hibernate引擎(上)
    Download a web page IronPython Cookbook
    豌豆荚工程师谈其新版应用搜索技术
    WebRequest.Proxy Property (System.Net)
    机器学习各类工具weka、scikitlearn等各项指标的对比
    Implementing a small Cron service in C# CodeProject
    Submit a POST form and download the result web page
    百度辜斯缪谈搜索引擎的未来——实体搜索
    python get with proxy
    R,不仅仅是一种语言
  • 原文地址:https://www.cnblogs.com/rioca/p/13463286.html
Copyright © 2020-2023  润新知