Python

  1. 记录Python中遇到的问题,方便之后查询,假如这种方式比Google快捷,便是赚到了

  2. Most pythonic way to delete a file which may not exist

    1
    2
    3
    4
    try:
    os.remove(filename)
    except OSError:
    pass
  1. format a floating number 尤其是不要出现可恶的科学计数法(编程中很难找到一种场景需要科学记数法)
    "{:10.4f}".format(x)

    or

    '% 6.2f' % v

  2. 处理日期

    1
    2
    time_test = dt.strptime(str_test, '%Y-%m-%d')
    str_out = dt.strftime(time_test, '%Y-%m-%d')

计算日期之间的差

1
2
3
(last_date - first_date).days
(last_date - first_date).seconds
可以根据这两项算小时的差

  1. pandas
  • set_index
  • apply 是非常重要的神器,例如这个例子

    1
    2
    3
    4
    5
    df['channel'] = df['wise_channel'].apply(lambda x:x.split("*")[0])
    ```
    5. [most pythonic way to pad a numeric string with zeroes to the left](http://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string)
    for strings

    i.zfill(3)

    1
    for numbers

    ‘{0:03d}’.format(4)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    6. 多进程
    7. logging 消息重复问题
    多次循环调用程序时,日志出现第一条记录打印一条,第二次记录打印两条,依次类推,导致后续大量重复的日志输出。原因是:重复调用logging,由于logger的name是一样的,每次调用都会添加handler,多个handler就会打印多条同样的日志记录。解决办法:存在handler就不重复创建了,直接返回logger。这一篇csdn的博客可以作为参考:[Python logging 重复写日志问题](http://blog.csdn.net/huilan_same/article/details/51858817)
    ```python
    logger = logging.getLogger(logname)
    if not logger.handlers:
    balabala...
    return logger
  1. if path does not exist create
    1
    2
    if not os.path.exists(directory):
    os.makedirs(directory)
  1. pythonic way to create 3d dict

    1
    json_dict = defaultdict(lambda: defaultdict(dict))
  2. 二维字典初始化

    1
    2
    from collections import defaultdict, Counter
    d = defaultdict(Counter)
  3. pythonic way to list all files of a directory in Python

  4. Display image as grayscale using matplotlib

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import numpy as np
    import matplotlib.pyplot as plt
    from PIL import Image
    fname = 'image.png'
    image = Image.open(fname).convert("L")
    arr = np.asarray(image)
    plt.imshow(arr, cmap='gray')
    plt.show()
  1. python的缩进是天使也是恶魔,尤其是使用vim的时候

  2. 不遵守pep8的都应该受惩罚

15.