Python入门:文件内容去重操作

发布时间:2019-08-23 08:00:52编辑:auto阅读(1354)


    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      学习是一种态度,只要你有态度,学习将会是一种乐趣
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    应用场景

    对行与行之间的重复内容进行删除
    如:从网上download几个常用的用户名或密码字典文件,但是合并的时候,肯定有很多是重复的,在使用这些内容进行暴力破解的时候,因为重复行,导致破解效率下降,所以需要进行简单修改,去重:

    #user.txt
    
    admin 
    root
    
    123
    user
    password 
     admin
    
    administrator

    应用代码

    #Author:foryouslg
    #python3.5
    '''
    1、对特定文件内容进行去重操作(行与行之间的重复)
    2、请输入需要去重文件的绝对路径
    3、删除文件中的空行
    4、去除字符串前后空行
    5、生成一个以当前日期命名的文件
    '''
    
    import time
    
    year = time.localtime().tm_year
    mon = time.localtime().tm_mon
    day = time.localtime().tm_mday
    hour = time.localtime().tm_hour
    min = time.localtime().tm_min
    sec = time.localtime().tm_sec
    nowtime = str(year) + str(mon) + str(day) + str(hour) + str(min) + str(sec)
    
    f = input("please entry the file[absolute path]:")
    
    def openThefile():
        '''
        1、打开要去重的文件
        2、删除每行数据前后的无用字符
        :return:
        '''
        ff = open(f,'r')
        l = []
        #for i in ff.readline():     #readline是文件中的第一行内容
        for i in ff.readlines():    #所有内容中的每一行
            if i != '\n' and i != '\r\n':   #删除空行
                ii = i.replace('\t','').strip()
                l.append(ii)
        ff.close()
        return l
    
    def createNewfile(openThefile):
        '''
        去重操作
        :param openThefile:
        :return:
        '''
        l = []
        for i in openThefile:
            if i not in l:
                l.append(i)
        '''
        创建新文件
        '''
        filename = f[:f.find('.')]
        postfix = f[f.find('.'):]
        theNewfile = open(filename + '_' + nowtime + postfix,'a')
        '''
        写入处理过的内容
        '''
        for i in l:
            theNewfile.writelines(i+'\n')
        theNewfile.close()
    
    
    
    if __name__ == '__main__':
        createNewfile(openThefile())

    执行后的结果

    admin
    root
    123
    user
    password
    administrator

关键字