Tuesday, March 11, 2014

Python 各种常用小功能

print后不换行

就是在命令后面加一个逗号。

print this,

当然这样写出来的代码到了3.3就不太管用了。所以还是老老实实用转义符吧,‘\r’

两列数字点乘

当然直接可以变成numpy.array然后乘起来,但如果不想为了这个小函数就加入一个依赖,那就这样:

from operator import mul

def dot(a_list, b_list):
    return map(mul, a_list, b_list)

将当前的时间输出成seconds from epochtime

import time, datetime
time.mktime(datetime.datetime.now().timetuple())

Written with StackEdit.

PDF merging without tears

I guess nobody needs a cumbersome Acrobat software to merge PDF files. And when things gets a little bit more complex, manually merging hundreds of PDFs can be a PIAS.

Use this:

from PyPDF2 import PdfFileMerger, PdfFileReader
import os


filenames = ["1.pdf", "2.pdf"]
merger = PdfFileMerger()
for filename in filenames:
    merger.append(PdfFileReader(file(os.path.join(os.getcwd(), filename), 'rb')))
merger.write(os.path.join(os.getcwd(), "output.pdf"))

It works like magic. Put this .py file to the folder where you would like to have some PDFs merged, change filenames, and modify this script. Life is instantly easier.

Written with StackEdit.