Python 我的方法

來源:互聯網
上載者:User

標籤:name   ip地址   gif   print   utf-8   color   內容   nbsp   空白   

def del_blank_line(filename):  # 清除檔案空白行    """    清除檔案空白行空白行    :param filename: 檔案名稱    :return: True 成功;False 失敗    """    try:        with open(filename, "r+", encoding="utf-8") as infp:            lines = infp.readlines()  # 把源檔案內容讀出來儲存在lines中        with open(filename, "w+", encoding="utf-8") as outfp:            for li in lines:                if li.split():  # 判斷是否為空白行                    outfp.writelines(li)  # 將操作後的源檔案覆蓋寫回    except IOError:        print("%s 檔案不存在或無操作許可權" % filename)        return False    else:        return True
清除檔案空白行
def get_ip_list(filename, repeat=False):    """    在檔案中擷取合法的IP地址    :param filename: 檔案名稱    :param repeat: 去除重複行,True去除,False不去除    :return: 返回ip地址序列    """    import re    try:        with open(filename, "r", encoding="utf-8") as file1:            line = file1.read()            pattern = re.compile(                r"(?:\b(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\b\.){3}(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\b")            list_ip = pattern.findall(line)            if len(list_ip) == 0:                return list_ip    except IOError:        print("%s 檔案不存在或無操作許可權" % filename)        return False    else:        if repeat == True:            return set(list_ip)        elif repeat == False:            return list_ip
在檔案中擷取合法的IP地址
def get_check_code(n = 6):    """    擷取有大小寫字母、數字組成的隨機n位驗證碼    :param num: 驗證碼位元,預設為6    :return: 返回n位驗證碼    """    import random    check_code = str()    code = str()    for i in range(n):        ret = random.randint(0, 9)        if ret == 0 or ret == 1 or ret == 4 or ret == 7:            code = str(ret)        elif ret == 2 or ret == 5 or ret == 8:            code = chr(random.randint(65, 90))        elif ret == 3 or ret == 6 or ret == 9:            code = chr(random.randint(97, 122))        check_code = check_code + code    return check_code
擷取n位隨機驗證碼

 

Python 我的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.