1. 程式人生 > >python 學習程式碼記錄

python 學習程式碼記錄

讀取文字內容,輸出列表

文字內容為
text,text,mic-text,mic-text,mic-text

with open("type.txt") as f1:
    type_ = f1.readlines()
print(type_)
type1 = ''.join(type_)
type2 = type1.split(',')

print(type1)
print(type2)

輸出
['text,text,mic-text,mic-text,mic-text']
text,text,mic-text,mic-text,mic-text
['text', 'text', 'mic-text', 'mic-text', 'mic-text']

數字輸出轉換大小 K,M等 ,可用在系統監控上

def bytes2human(n):

    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.2f %s' % (value, s)
    return '%.2f B' % (n)

a = bytes2human(1024)
print(a)
輸出
1.00 K

獲取本地時間,轉成UTC時間(在中國utc時間就是減8個小時)

def local2utc(local_st):
    time_struct = time.mktime(local_st.timetuple())
    utc_st = datetime.utcfromtimestamp(time_struct)
    return utc_st
    
year = int(time.strftime("%Y"))
month = int(time.strftime("%m"))
day = int(time.strftime("%d"))
hour = int(time.strftime("%H"))
minute = int(time.strftime("%M"))
second = int(time.strftime("%S"))
local_time = datetime(year, month, day, hour, minute, second)
utc_time = local2utc(local_time)

使用linux命令

os.system(‘mv xxx.py data/’)

configparser,讀取ini配置檔案

import configparser
cf = configparser.ConfigParser()
cf.read("config.conf")
print(cf.sections())
print(cf.options("first"))
print(cf.get("first", "host"))

class myconf(configparser.ConfigParser):
    def __init__(self, defaults=None):
    configparser.ConfigParser.__init__(self, defaults=defaults)
# 這裡重寫了optionxform方法,返回的key會仍為原樣,不會都為小寫了
    def optionxform(self, optionstr):
        return optionstr

windows電腦右下角顯示小視窗

from win10toast import ToastNotifier

toaster = ToastNotifier()
toaster.show_toast("hello world", "python", duration=10)

統計文字單詞出現最多及個數

def count_words(s, n):
    """Return the n most frequently occuring words in s."""
    w = {}
    sp = s.split()
    # TODO: Count the number of occurences of each word in s
    for i in sp:
        if i not in w:
            w[i] = 1
        else:
            w[i] += 1
    # TODO: Sort the occurences in descending order (alphabetically in case of ties)
    top = sorted(w.items(), key=lambda item:(-item[1], item[0]))
    top_n = top[:n]
    # TODO: Return the top n most frequent words.
    return top_n

def test_run():
    """Test count_words() with some inputs."""
    print(count_words("cat bat mat cat bat cat", 3))
    print (count_words("betty bought a bit of butter but the butter was bitter", 3))

if __name__ == '__main__':
    test_run()

python 1加到100

from functools import reduce
def add(x, y):
    return x + y
num_list = [num for num in range(1, 101)]
a = reduce(add, num_list)
print(a)

輸出:
5050

查詢天氣

import requests

city_code = {"北京": "101010100", "上海": "101020100", "天津": "101030100", "深圳": "101280601", "南昌": "101240101"}
city = input("輸入城市\n")
code = city_code[city]
url = 'http://wthrcdn.etouch.cn/weather_mini'
payload = {"citykey": code}
result = requests.get(url, params=payload)
res = result.json()["data"]["forecast"][0]
today_type = res["type"]
today_low = res["low"]
today_high = res["high"]
tem = today_low.split(" ")[1] + " ~ " + today_high.split(" ")[1]
print(tem)
print(today_type)

itchart下載微信頭像,獲取相關資訊

#_*_ coding:utf-8 _*_

import itchat
itchat.auto_login()
for friend in itchat.get_friends(update=True)[0:]:
    #可以用此句print檢視好友的微信名、備註名、性別、省份、個性簽名(1:男 2:女 0:性別不詳)
    print(friend['NickName'],friend['RemarkName'],friend['Sex'],friend['Province'],friend['Signature'])
    img = itchat.get_head_img(userName=friend["UserName"])
    path = "20181030/"+friend['NickName']+"("+friend['RemarkName']+").jpg"
    try:
        with open(path, 'wb') as f:
            f.write(img)
    except Exception as e:
        print(repr(e))
itchat.run()

pyecharts畫柱狀圖

from pyecharts import Bar

attr = ["面膜", "眼鏡", "口罩", "鼻貼", "帽子", "劉海"]
v1 = [0.952, 0.974, 0.969, 0.965, 0.961, 0.952]
v2 = [1.0, 0.963, 0.974, 0.923, 0.953, 0.916]
v3 = [0.816, 0.838, 0.938, 0.8, 0.854, 0.804]
bar = Bar("評價指標")
# bar_category 類目軸的柱狀距離,預設為 20, is_label_show 顯示數值, yaxis_max y軸的最大值
bar.add("準確率", attr, v1, bar_category_gap=15, is_label_show=True, yaxis_max=1.2)
bar.add("精確率", attr, v2, bar_category_gap=15, is_label_show=True, yaxis_max=1.2)
bar.add("召回率", attr, v3, bar_category_gap=15, is_label_show=True, yaxis_max=1.2)
bar.render()

讀取xml檔案

# -*- coding: utf-8 -*-

# from xml.etree.ElementTree import parse
from lxml.etree import parse        # 或者使用lxml.etree,推薦用這個
import os
import glob
import pandas as pd

path = "all_xml/"
input_path = os.path.join(path, "*l")
xml_paths = glob.glob(input_path)
all_list = list()
filename_list = list()
for xml in xml_paths:
    doc = parse(xml)
    filename = doc.findtext('filename')
    type_list = list()
    type_dict = dict()
    for item in doc.iterfind('object'):
        name = item.findtext('name')
        type_list.append(name)
    for i in type_list:
        if i in type_dict:
            type_dict[i] += 1
        else:
            type_dict[i] = 1
    filename_list.append(filename)
    all_list.append(type_dict)
df = pd.DataFrame(all_list, index=filename_list)
df.to_excel("result.xlsx")