Python Tips (Continue...)

2016-08-04  本文已影响151人  一个不知死活的胖子

导语

Python有好多非常实用的函数总是让人觉得相见恨晚!(握拳)

String

str.startswith(startStr)
print "{0} and {1} are couple.".format('Rose', 'Jack')
# which is equal to 
print "%s and %s are couple." % (Rose', 'Jack')

# print string with equal width
print "{0:10} | {0:10} | {0:10}".format(str1, str2, str3)

List

" ".join(list)  # use a space to join the list

Dict

from collections import defaultdict

"""
dataType can be null, or can be claimed with certain data type
"""
dict = defaultdict(dataType)

Date

from dateutil.parser import parse

date = parse(dateString)
day = date.days

DataFrame

"""
ATTENTION: return a dataframe with distinct values of this COLUMN serving as index
"""
df['COLUMN'].value_counts()
df.to_csv('df.csv', index = False)

编码

关于中文的编码问题笔者只能感到惆怅……这时一定会提到一个包:codecs

import codecs

# open csv/txt file with utf-8 encoding
csvFile = codecs.open('csvFile.csv', encoding = 'utf-8')
csv.write('XXX')
with open('csvFile.csv', 'w') as csvFile:
    csvFile.write(codecs.BOM_UTF8)
    csvFile.write('XXX')

若希望在读取文件之前删除BOM头:

csvFile = codecs.open('csvFile', 'r', 'utf_8_sig')

当然,若文件不大的话,也可以使用编辑器进行转码,例如:notepad++、ultraedit

Terminal

让Terminal的输出有字体颜色差异:

STYLE = {
        'fore': {
                'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
                'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37,
        },
        'back': {
                'black': 40, 'red': 41, 'green': 42, 'yellow': 43,
                'blue': 44, 'purple': 45, 'cyan': 46, 'white': 47,
        },
        'mode': {
                'bold': 1, 'underline': 4, 'blink': 5, 'invert': 7,
        },
        'default': {
                'end': 0,
        }
}

def use_style(string, mode='', fore='', back=''):
    mode = '%s' % STYLE['mode'][mode] if STYLE['mode'].has_key(mode) else ''
    fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].has_key(fore) else ''
    back = '%s' % STYLE['back'][back] if STYLE['back'].has_key(back) else ''
    style = ';'.join([s for s in [mode, fore, back] if s])
    style = '\033[%sm' % style if style else ''
    end = '\033[%sm' % STYLE['default']['end'] if style else ''
    return '%s%s%s' % (style, string, end)

# example print
print use_style('Hello World!', mode='bold', fore='red')
上一篇下一篇

猜你喜欢

热点阅读