读取文本内容,输出列表
文本内容为
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")