当前所在位置: 首页 > 生活常识 > 正文

python代码大全和用法(python代码命令大全)

2023-01-21 canyinms.com 【 字体:

python代码大全和用法,python,代码命令大全。小编来告诉你更多相关信息。

一些常用的python代码合集,方便检索引用

模块1:读写excel文件

from datetime import datetime

python代码大全和用法(python代码命令大全)

import odps

import xlwt

import os

from odps import DataFrame

import pandas as pd

import xlrd

import numpy as np

from collections import defaultdict

from collections import Counter

def write_imf(fl_save_path, data):

sh = wb.add_sheet(u\'data\', cell_overwrite_ok=True)

colnames = data.columns.values

for i in range(0, data.shape[1]):

sh.write(0, i, colnames[i])

for i in range(1, len(data) + 1):

for j in range(0, data.shape[1]):

value = data.iloc[i - 1, j]

try:

value.dtype

if value.dtype == \'int64\':

value = int(value)

if value.dtype == \'float64\':

value = float(value)

except(RuntimeError, TypeError, NameError, ValueError, AttributeError):

pass

sh.write(i, j, value)

wb.save(fl_save_path)

print(\'congratulation save successful!\')

def save_pd_to_csv(fl_save_path, data):

return True

except:

return False

def get_excel_content(file_path):

wb = xlrd.open_workbook(file_path, encoding_override=\'utf-8\')

wb_cont_imf = []

df = pd.DataFrame(wb_cont_imf[1:], columns=wb_cont_imf[0])

return df

模块2:获取各种时间

def getMonthFirstDayAndLastDay(year=None, month=None):

:param year: 年份,默认是本年,可传int或str类型

:param month: 月份,默认是本月,可传int或str类型

:return: firstDay: 当月的第一天,datetime.date类型

lastDay: 当月的最后一天,datetime.date类型

if year:

year = int(year)

else:

year = datetime.date.today().year

if month:

month = int(month)

else:

month = datetime.date.today().month

firstDayWeekDay, monthRange = calendar.monthrange(year, month)

firstDay = datetime.date(year=year, month=month, day=1)

lastDay = datetime.date(year=year, month=month, day=monthRange)

return lastDay

模块3:pd中的dataframe转png

def render_mpl_table(data, col_width=5.0, row_height=0.625, font_size=1,

bbox=[0, 0, 1, 1], header_columns=0,

ax=None,**kwargs):

if ax is None:

plt.style.use(\'ggplot\')

ax.axis(\'off\')

mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)

mpl_table.auto_set_font_size(False)

mpl_table.set_fontsize(font_size)

for k, cell in six.iteritems(mpl_table._cells):

cell.set_edgecolor(edge_color)

nrow = k[0]

ncol = k[1]

if nrow == 0 or ncol < header_columns:

cell.set_text_props(weight=\'bold\', color=\'w\')

cell.set_facecolor(header_color)

else:

cell.set_facecolor(row_colors[k[0] % len(row_colors)])

plt.gca().xaxis.set_major_locator(plt.NullLocator())

plt.gca().yaxis.set_major_locator(plt.NullLocator())

plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)

plt.margins(0, 0)

return ax

模块4:绘制词云

_author_ = \'xisuo\'

import datetime

import calendar

import xlwt

import os

import pandas as pd

import xlrd

import openpyxl

import numpy as np

from collections import defaultdict

import platform

from wordcloud import WordCloud,STOPWORDS

import matplotlib.pyplot as plt

from PIL import Image

def create_wordcloud(docs=None,imgs=None,filename=None):

:param docs:读入词汇txt,尽量不重复

:param imgs: 读入想要生成的图形,网上随便找

:param filename: 保存图片文件名

:return:

text = open(os.path.join(current_file, docs)).read()

alice_mask = np.array(Image.open(os.path.join(current_file, imgs)))

print(font_path)

wc = WordCloud(background_color=\"white\",

max_words=2000,

mask=alice_mask,

stopwords=STOPWORDS.add(\"said\")

)

wc.generate(text)

if filename is None:filename=\"词云结果.png\"

wc.to_file(os.path.join(current_file, filename))

def main():

create_wordcloud(docs=docs,imgs=imgs,filename=filename)

print(\'create wordcloud successful\')

if __name__ == \'__main__\':

start_time = datetime.datetime.now()

print(\'start running program at:%s\' % start_time)

systemp_type = platform.system()

if (systemp_type == \'Windows\'):

font_path=\'simfang.ttf\'

try:

current_path = os.getcwd()

except:

current_path = os.path.dirname(__file__)

current_file = os.path.join(current_path, \'docs\')

current_file = current_path

elif (systemp_type == \'Linux\'):

font_path = \'Arial Unicode MS.ttf\'

else:

quit()

if not os.path.exists(current_file):

os.mkdir(current_file)

print(\'目录中部存在docs文件夹,完成新文件夹创建过程。\')

print(\'当前操作系统:%s,文件存储路径为:%s\' % (systemp_type, current_file))

main()

end_time = datetime.datetime.now()

tt = end_time - start_timepython

print(\'ending time:%s\', end_time)

print(\'this analysis total spend time:%s\' % tt.seconds)

模块5:下载ppt素材

_author_ = \'xisuo\'

import urllib.request

import requests

from bs4 import BeautifulSoup

from lxml import etree

import os

response=requests.get(url).text

html=etree.HTML(response)

src_list=html.xpath(\'//div/article/p/img/@src\')

current_path=os.path.dirname(__file__)

save_path=os.path.join(current_path,\'ppt_img\')

if os.path.exists(save_path):

os.mkdir(save_path)

print(\'img folder create successful\')

for src in src_list:

save_img_path=os.path.join(save_path,\'%d.jpg\'%i)

with open(save_img_path,\'wb\') as f:

f.write(urllib.request.urlopen(src).read())

f.close()

i=i+1

print(\'save true\')

except Exception as e:

print(\'save img fail\')

模块6:模型存储和读取

rom sklearn import joblib

from sklearn import svm

from sklearn2pmml import PMMLPipeline, sklearn2pmml

import pickle

def save_model(train_X,train_y):

save model

:return:

clf = svm.SVC()

clf.fit(X, y)

joblib.dump(clf, \"train_model.m\")

sklearn2pmml(clf, \"train_model.pmml\")

with open(\'train_model.pickle\', \'wb\') as f:

pickle.dump(clf, f)

return True

def load_model():

laod model

:return:

clf_joblib=joblib.load(\'train_model.m\')

clf_pickle== pickle.load(open(\'linearregression.pickle\',\'rb\'))

return clf_joblib,clf_pickle

模块7:TF-IDF

import time

import pandas as pd

import numpy as np

from sklearn.feature_extraction.text import CountVectorizer

from sklearn.feature_extraction.text import TfidfVectorizer

print(\'开始读取KeyTag标签...\')

read_data_path = \'D:/untitled/incomelevel_kwtag_20190801.txt\'

load_data = pd.read_csv(read_data_path, sep=\'\\t\',encoding=\'utf-8\')

data = pd.DataFrame(load_data,columns = [\'income_level\',\'kw_tag\'])

print(\'...读取KeyTag标签完成\')

print(\'开始分组处理KeyTag标签...\')

incomelevel_top = data[data[\'income_level\'] == \'高\']

kw_tag_top = \' \'.join(incomelevel_top[\'kw_tag\'])

print(\'kw_tag_top : \\n\',kw_tag_top)

incomelevel_mid = data[data[\'income_level\'] == \'中\']

kw_tag_mid = \' \'.join(incomelevel_mid[\'kw_tag\'])

print(\'kw_tag_mid : \\n\',kw_tag_mid)

incomelevel_low = data[data[\'income_level\'] == \'低\']

kw_tag_low = \' \'.join(incomelevel_low[\'kw_tag\'])

print(\'kw_tag_low : \\n\',kw_tag_low)

print(\'...分组处理KeyTag标签完成\')

vectorizer = CountVectorizer()

result = vectorizer.fit_transform([kw_tag_top, kw_tag_mid, kw_tag_low])

transformer = TfidfVectorizer()

kw_tag_score = transformer.fit_transform([kw_tag_top, kw_tag_mid, kw_tag_low])

print(\'...KeyTag分词结束\')

kw_tag_value = transformer.get_feature_names()

result_target = pd.DataFrame(kw_tag_value,columns = [\'kw_tag\'])

print(\'result_target : \\n\',result_target)

tf_score = kw_tag_score.toarray()

print(\'tf_score : \\n\',tf_score)

kw_tag_score_mid = pd.DataFrame(tf_score[1],columns = [\'kw_tag_score_mid\'])

kw_tag_score_low = pd.DataFrame(tf_score[2],columns = [\'kw_tag_score_low\'])

print(len(kw_tag_score_top))

模块8:生成省市地图

import time

import pandas as pd

import xlrd

import re

import matplotlib.pyplot as plt

import six

import numpy as np

from pyecharts.render import make_snapshot

from snapshot_phantomjs import snapshot

from pyecharts import options as opts

from collections import defaultdict

from pyecharts.charts import Bar, Geo, Map, Line,Funnel,Page

import os

from example.commons import Faker

def create_zjs_map():

folder_path = os.getcwd()

file_name = \"白皮书数据地图.xlsx\"

file_path = os.path.join(folder_path, file_name)

dat = get_excel_content(file_path, sheet_name=\"省份地图\")

df = dat[[\'城市\', \'渗透率\']]

df.columns = [\'city\', \'penarate\']

print(df)

citys = df[\'city\'].values.tolist()

values = df[\'penarate\'].values.tolist()

print(citys)

print(\'{:.0f}%\'.format(max(values)*100),\'{:.0f}%\'.format(min(values)*100))

city_name=\'浙江\'

penetration_map = (

Map(init_opts=opts.InitOpts(width=\'1200px\', height=\'1000px\', bg_color=\'white\'))

.add(\"{}透率分布\".format(city_name), [list(z) for z in zip(citys, values)], city_name)

.set_series_opts(

label_opts=opts.LabelOpts(

is_show=True,

font_size=15

)

)

.set_global_opts(

visualmap_opts=opts.VisualMapOpts(

is_show=True,

max_=max(values),

min_=min(values),

is_calculable=False,

orient=\'horizontal\',

split_number=3,

range_text=[\'{:.0f}%\'.format(max(values)*100),\'{:.0f}%\'.format(min(values)*100)],

pos_left=\'10%\',

pos_bottom=\'15%\'

),

legend_opts=opts.LegendOpts(is_show=False)

)

make_snapshot(snapshot, penetration_map.render(), \"zj_map.png\")

print(\'保存 zj_map.png\')

return penetration_map

def create_county_map(city_name):

folder_path = os.getcwd()

file_name = \"白皮书数据地图.xlsx\"

file_path = os.path.join(folder_path, file_name)

dat = get_excel_content(file_path, sheet_name=\"城市地图\")

df = dat[[\'city\', \'county\', \'penarate\']][dat.city == city_name]

citys = df[\'county\'].values.tolist()

values = df[\'penarate\'].values.tolist()

max_insurance = max(values)

print(citys)

province_penetration_map = (

Map(init_opts=opts.InitOpts(width=\'1200px\', height=\'1000px\', bg_color=\'white\'))

.add(\"{}透率分布\".format(city_name), [list(z) for z in zip(citys, values)], reg.sub(\'\',city_name))

.set_series_opts(

label_opts=opts.LabelOpts(

is_show=True,

font_size=15

)

)

.set_global_opts(

visualmap_opts=opts.VisualMapOpts(

is_show=True,

max_=max(values),

min_=min(values),

is_calculable=False,

orient=\'horizontal\',

split_number=3,

range_text=[\'{:.0f}%\'.format(max(values) * 100), \'{:.0f}%\'.format(min(values) * 100)],

pos_left=\'10%\',

pos_bottom=\'5%\'

),

legend_opts=opts.LegendOpts(is_show=False)

)

make_snapshot(snapshot, province_penetration_map.render(), \"city_map_{}.png\".format(city_name))

print(\'保存 city_map_{}.png\'.format(city_name))

return province_penetration_map

def create_funnel_label():

folder_path=os.getcwd()

file_name = \"白皮书数据地图.xlsx\"

file_path = os.path.join(folder_path, file_name)

dat = get_excel_content(file_path, sheet_name=\"漏斗图\")

df = dat[[\'category\', \'cnt\']]

print(df)

category = df[\'category\'].values.tolist()

values = df[\'cnt\'].values.tolist()

funnel_map = (

Funnel(init_opts=opts.InitOpts(width=\'1200px\', height=\'1000px\', bg_color=\'white\'))

.add(\"漏斗图\", [list(z) for z in zip(category, values)])

.set_series_opts(

label_opts=opts.LabelOpts(

position=\'inside\',

font_size=16,

)

)

.set_global_opts(

legend_opts=opts.LegendOpts(is_show=False)

)

make_snapshot(snapshot, funnel_map.render(), \"funnel.png\")

print(\'保存 funnel.png\')

return funnel_map

city_list=[\'温州市\',\'杭州市\',\'绍兴市\',\'嘉兴市\',\'湖州市\',\'宁波市\',\'金华市\',\'台州市\',\'衢州市\',\'丽水市\',\'舟山市\']

for city_name in city_list:

create_county_map(city_name)

阅读全文
相关推荐

如何自制蛋挞

如何自制蛋挞
1、倒入低筋面、黄油和水,揉成面团状,藏一小时后取出,抹上黄油卷起,包上保鲜膜冷藏半小时。2、取出,将面团切成一厘米的面团,放入模具内,用力按压,中间稍薄,外缘要比模具高,将蛋挞液倒入蛋挞皮中,放入烤箱里烤30分钟即可。

肉火烧面怎么和面

肉火烧面怎么和面
1、首先用温水把酵母融开,加入面粉,用手把面粉揉成非常软的面团,可以放一点熬好的猪油在面团里面。2、然后放在温暖的地方,盖上保鲜膜发酵至2倍大,发好的面团用手插入不回缩,就说明面团发酵好了。

奶茶几分糖好喝

奶茶几分糖好喝
1、不同的人对奶茶的口感要求是不一样的,一般来说,奶茶有三分糖、五分糖、七分糖三种不同的口味。2、女生一般都喜欢喝甜一点的,而男生则喜欢喝不那么甜的,七分糖的奶茶最好喝。

过桥米线是哪里的?

过桥米线是哪里的?
过桥米线是来自云南省滇南地区的一种有名特色小吃。过桥米线最早是在清朝就已经出现,距离现在至少有一百多年的历史啦!起源于建水县东城外锁龙桥西侧的鸡市街头处,有建水的特产草芽、地椒作配料,风味独特而远近闻名。深受广大美食爱好者的喜欢,不少人为此专门长途跋涉,只为尝

面霜和乳液的区别

面霜和乳液的区别
面霜和乳液的区别,相较而言乳液的水分含量要比面霜高,乳液质地要轻薄一些,乳液主要作用是保湿,滋润可以隔离外界干燥的气候,面霜既可保湿,又可美白,还能抗衰老,乳液的吸收快一些,而面霜吸收比较慢一些,因为液体的吸收速度都比较快。

怎么摘隐形眼镜

怎么摘隐形眼镜
在摘隐形眼镜之前,先用洗手液将手清洗干净,以免将细菌带入眼睛内,对着镜子,用右手中指轻拉眼睛下眼睑,左手中指轻拉眼睛上眼睑,让黑色眼球暴露在空气中,用右手食指和拇指轻触镜片的两边缘部分,向中间推使镜片拱起,再用两手指轻轻捏出镜片即可。

粉饼和散粉的区别

粉饼和散粉的区别
粉饼是呈压缩固体状态,多呈圆形或者方形,散粉则是细腻的粉末状,粉饼遮瑕力会比较强一些,可以湿用做粉底,或者用来补妆,而散粉则是定妆的效果,粉饼通常用在底妆的第一步,而散粉通常用在底妆最后一步。

冷烫和热烫的区别

冷烫和热烫的区别
冷烫和热烫的区别:冷烫对头发的要求是要在保温状态下才能给卷有个好的效果,而热烫是在干和湿的情况下都行,热烫烫出来的头发比较自然明显而有弹力,冷烫的头发风干后基本看不出来,并且发质会有点干。

高品质香水如何鉴别?用三步就可以解决

高品质香水如何鉴别?用三步就可以解决
1、看色泽以天然香料调制而成的高级香水,都有它本来的颜色,且大都是琥珀色或褐色,看起来很像宝石,比如,从茉莉、玫瑰或水仙等天然鲜花中所萃取的精油都呈黄色、褐白或绿褐色;此外,香水中所添加的魅惑香气物性香料也是褐色,苔类中的橡树苔是绿色,从树根或树根脂类中萃取的

如何去除黑眼圈

如何去除黑眼圈
去除黑眼圈首先可以用热毛巾敷眼,然后再用冷毛巾敷,十分钟就能让黑眼圈淡化的不那么严重,其次将去壳后的鸡蛋用无菌纱布包裹住,敷于眼部轻轻转动,可以急救去除黑眼圈,另外抹完眼霜后,用双手顺时针按摩,可以促进血液循环消除黑眼圈。
本文Tag