Python的一些小知识点_3


检查指定文件是否存在:
import os
os.path.isfile(fname)

import os.path
os.path.exists(file_path)
list合并的方法:
mergedlist = listone + listtwo

参考http://stackoverflow.com/questions/1720421/merge-two-lists-in-python

Python中list和tuple的不同:
Python返回内容的一些tips:

http://stackoverflow.com/questions/363944/python-idiom-to-return-first-item-or-none

Python的idioms:

http://stackoverflow.com/search?tab=votes&q=python%20idioms

Python的Luhn算法实现:
def luhn_checksum(card_number):
    def digits_of(n):
        return [int(d) for d in str(n)]
    digits = digits_of(card_number)
    odd_digits = digits[-1::-2]
    even_digits = digits[-2::-2]
    checksum = 0
    checksum += sum(odd_digits)
    for d in even_digits:
        checksum += sum(digits_of(d*2))
    return checksum % 10

def is_luhn_valid(card_number):
    return luhn_checksum(card_number) == 0
参考链接:

如何获取Python的迭代器的长度

刚才在看扫描MongoDB的未授权连接的代码时,看到的一段生成字典的Python片段,很给力啊,用到了Python的迭代器(itertools),然后在验证脚本效果的时候直接用了len()函数,没想到会报错“TypeError: object of type ‘generator’ has no len()

网上搜索了之后找到解决办法,值得记录一下:
http://cn.bing.com/search?q=type+%27generator%27++len%28%29

import itertools
def genBrute(chars, maxLen):
    return (''.join(candidate) for candidate in itertools.chain.from_iterable(itertools.product(chars, repeat=i) for i in range(1, maxLen + 1)))

#print len(genBrute(chainSet,int(maxLen)))   # TypeError: object of type 'generator' has no len()
print len( list(genBrute(chainSet,int(maxLen))) )
打印list/tuple等可迭代对象(iterable)的一个tips
print "List of databases:"
print "n".join(dbList)

#之前的方法是手动for循环:
for item in dbList:
    print item
'''
但是存在的问题在于:
1.代码不够简短;
2.没法指定分隔符(虽然可以在'print item'后面添加一个逗号,但不够方便)
'''
在Python中如何判定一个对象是否为可迭代(iterable)的?

判定方法就是:
1.iter()函数
2.hasattr(object_name, ‘__iter__’)
3.引入collections中的方法

import collections
if isinstance(theElement, collections.Iterable):
     # iterable
else:
     # not iterable
#TODO:对大文件的处理(不读至内存,慢慢迭代)
def fileToList(fileName):
    lineList = []
    try:
        fileParser = open(fileName, 'r')
    except IOError as ioerr:
        print "[!] open file error: n   " + str(ioerr)
    except:
        print "[!] can't access the file: %s " % fileName
    for line in fileParser:		'''' 在Python中如何判断一个对象是"可迭代的" '''
        newLine = line.strip()
        lineList.append(newLine)
    fileParser.close()
return lineList
参考链接:
用Python发送邮件_1
#!/usr/bin/env python
# coding=utf-8
import smtplib
from email.Message import Message
import time

def sendMail(user, passwd):
    systemTime=time.strftime('%Y-%m-%d',time.localtime(time.time()))
    try:
        fileObj=open(r"F:xianguo.opml", "r")
        content=fileObj.read()
    except:
        print "Cannot read filen"
        exit()
    message = Message()
    message['Subject'] = 'Connect test'
    message['From'] = user
    message['To'] = "[email protected]"
    message.set_payload("The time ist"+systemTime+"n"+content)
    msg = message.as_string()

    smtp = smtplib.SMTP("smtp.126.com", port=25, timeout=20)
    #sm.set_debuglevel(1)   #开启debug模式
    #smtp.starttls()        #使用安全连接
    #smtp.ehlo()
    smtp.login(user, passwd)
    smtp.sendmail(user, "[email protected]", msg)
    time.sleep(5)   #避免邮件没有发送完成就调用了quit()
    smtp.quit()

if __name__=="__main__":
    emailName="[email protected]"
    emailPasswd="haha,man."
    sendMail(emailName, emailPasswd)
用Python发送邮件_2
#!/usr/bin/env python
# coding = utf-8
import smtplib
from email.mime.text import MIMEText
import urllib2
import json
import time

url = "http://www.v2ex.com/api/topics/hot.json"
user_name = "[email protected]"
passwd = "password"
smtp_serv = "smtp.126.com"
send_to = "[email protected]"

class SendMail:
    def __init__(self, username, passwd, serv_addr):
        self.__username = username
        self.__passwd = passwd
        self.__serv = smtplib.SMTP(serv_addr, port=25, timeout=20)

    def __login(self):
        self.__serv.login(self.__username, self.__passwd)

    def sendmsg(self, mail_to, subject, content):
        self.__login()
        msg = MIMEText(content)
        msg['Subject'] = subject
        msg['From'] = self.__username
        msg['To'] = mail_to
        self.__serv.sendmail(self.__username, mail_to, msg.as_string())
        self.__serv.quit()

def build_msg():
    res = urllib2.urlopen(url).read()
    json_res = json.loads(res)
    msg = []
    id = 0
    for top in json_res:
        id = id + 1
        msg.append(str(id)+": ")
        msg.append(top['url'].encode('utf-8'))
        msg.append("rnrn")
        msg.append("Title:  ")
        msg.append(top['title'].encode('utf-8'))
        msg.append("rnrn")
        msg.append("Content:  ")
        msg.append(top['content'].encode('utf-8'))
        msg.append("rnrn")
    return msg

if __name__ == "__main__":
    send = SendMail(user_name, passwd, smtp_serv)
    today = time.strftime("%Y-%m-%d", time.localtime(time.time()))
    title = "v2ex top 10 @ " + today
    print title
    msg = build_msg()
    str_msg = ''.join(msg)
    send.sendmsg(send_to, title, str_msg)

 

, ,

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注