-
1、python将print输出的信息保留到文件中
#清空记事本内容 事先需要先建立文件
with open("test_print.txt", 'r+') as file:
file.truncate(0)
doc=open("D:\\aaa\\test_print.txt",'a')
for i in range(5):
print(i,file=doc)
doc.close()
模式 | 可做操作 | 若文件不存在 | 是否覆盖 |
r | 只能读 | 报错 | - |
r+ | 可读可写 | 报错 | 是 |
w | 只能写 | 创建 | 是 |
w+ | 可读可写 | 创建 | 是 |
a | 只能写 | 创建 | 否,追加写 |
a+ | 可读可写 | 创建 | 否,追加写 |
参考链接:点此链接
-
2、导入自己的包
#导入自己的包
import os
origin="E:/chinakeji/haidian/python/written/"
os.chdir(origin)
import AREA
-
3、在python中,None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False
# -*- coding: utf-8 -*- """ 在python中,None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False """ words=None print(not words) words=False print(not words) words="" print(not words) words=0 print(not words) words=[] print(not words) words={} print(not words) words=() print(not words)
-
4、if __name__ == '__main__':的运行原理
每个python模块(python文件,也就是此处的 test.py 和 import_test.py)都包含内置的变量 __name__,当该模块被直接执行的时候,__name__ 等于文件名(包含后缀 .py );如果该模块 import 到其他模块中,则该模块的 __name__ 等于模块名称(不包含后缀.py)。
而 “__main__” 始终指当前执行模块的名称(包含后缀.py)。进而当模块被直接执行时,__name__ == 'main' 结果为真。
参考链接:点此链接
-
5、//、/、%
# /是真除法。
3/2=1.5
# 如果想在python3使用地板除,是//
3//2=1
# %表示求余数
5%2=1
-
6、python子类继承父类及初始化
class A(object):
def __init__(self,xing,gender):
self.namea="aaa"
self.xing = xing
self.gender = gender
def funca(self):
print("function a : %s"%self.namea)
class B(A):
def __init__(self,xing,gender,age): #但与类A中参数名相对应,
super(B,self).__init__(xing,age)
self.nameb="bbb"
# self.namea="ccc" #B类中有同名属性时,覆盖A类中的同名属性
self.xing = xing.upper()
self.age = age + 1
# self.gender = gender.upper() #注释这句 因为b没有对gender初始化,而只是对age初始化,故这个age参数是赋值到A类的gender参数上
def funcb(self):
print("function b : %s"%self.nameb) #
b=B("lin","nan",22)
print(b.nameb)
print(b.namea)
print(b.xing)
print(b.age)
b.funcb()
b.funca()
print(b.gender) #####
#22 因为b没有对gender初始化,而只是对age初始化,故这个age参数是赋值到A类的gender参数上
正解:点此链接
参考链接:点此链接
]调试:设置好断点之后按ctrl+F5(鼠标点击图标一样)即进入调试模式。
单行执行:Ctrl+F10 单行执行。
进入函数内部:执行到断点位置之后需要进入函数内部,则按ctrl+F11。
跳出函数:按Ctrl+Shift+F11 后会直接跳到该函数的执行的最后一行,此时在按一遍Ctrl+Shift+F11 或 者Ctrl+F10 (单行执行)就可以跳出函数
执行到下一个断点:c命令或者Ctrl+F12可以让程序执行到下一个断点。
快捷键
-
8、log() 函数
import math
math.log(x[, base])
-
9、使用
dict
时,如果引用的Key不存在,就会抛出KeyError
。如果希望key不存在时,返回一个默认值,就可以用defaultdict
:
from collections import defaultdict
dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
print(dict1[1]) #0
print(dict2[1]) #set()
print(dict3[1]) #
print(dict4[1]) #[]
#实际使用
word_dict = defaultdict(float)
word='丁真'
if not word_dict[word]:
word_dict[word] = 1
else:
word_dict[word] += 1
参考链接:点此链接
-
10、with open()的使用方法
方法一:with open()
用途:是python用来打开本地文件的,他会在使用完毕后,自动关闭文件,无需手动书写close()
with open(corpus_path, "r", encoding='UTF-8') as f:
for line in f:
print(line)
print("="*30)
方法二: 定义函数
#读取文本文件
def read_from_file(directions):
decode_set=['utf-8','gb18030','ISO-8859-2','gb2312','gbk','Error']#编码集
#编码集循环
for k in decode_set:
try:
file = open(directions,"r",encoding=k)
readfile = file.read()#这步如果解码失败就会引起错误,跳到except。
#print("open file %s with encoding %s" %(directions,k))#打印读取成功
#readfile = readfile.encode(encoding="utf-8",errors="replace")#若是混合编码则将不可编码的字符替换为"?"。
file.close()
break#打开路径成功跳出编码匹配
except:
if k=="Error":#如果碰到这个程序终止运行
raise Exception("%s had no way to decode"%directions)
continue
return readfile
#读取文件
file_data = str(read_from_file('射雕英雄传txt精校版.txt'))
-
11、python的 @staticmethod,@classmethod和@property的区别
这些装饰器都是用来装饰类里面的方法的,他们都是有什么用处呢?
首先,类的一般来说需要实例化后才能调用。但是使用了这前面两个装饰器,就可以不用实例化就可以直接调用类了。
直接 类名.方法名() 来调用。
这样有助于组织代码。
但是他们两个还是有区别的。
@staticmethod 不需要表示自身对象的self和自身类的cls参数,就和使用普通的函数一样。
@classmethod 不需要self参数,但是第一个cls参数需要表示自身类的cls参数。
简而言之,在类里有@staticmethod的,可以直接调用,没有加上改装饰器的方法就不能去调用。
@classmethod的话,在类里的所有方法都可以调用的。
class A(object):
bar = 1
def foo(self):
print(' call function foo in class A ')
@staticmethod
def static_foo():
print('static_foo')
print(A.bar)
@classmethod
def class_foo(cls):
print('class_foo')
print(cls.bar)
cls().foo()
执行结果:
@property装饰器的作用在调用的时候不用加()
class A(object):
def __init__(self,name,age):
self.name = name
self.age = age
@property
def static_foo(self):
print(self.name)
return 'yes'
num = A("Liu","21")
num.static_foo
执行结果:
参考链接:点此链接
-
12、类私有属性:只需要在初始化时,在属性名前加__
私有属性:只需要在初始化时,在属性名前加__
class Cup:
#构造函数,初始化属性值
def __init__(self,capacity,color):
#私有属性,只需要在属性名字前加__
self.__capacity=capacity
self.color=color
def retain_water(self):
print("杯子颜色:"+self.color+",杯子容量:"+self.__capacity+",正在装水.")
def keep_warm(self):
print("杯子颜色:"+self.color+",杯子容量:"+self.__capacity+",正在保温.")
currentCup=Cup('50ml','紫色')
currentCup.retain_water()
执行结果:
私有方法:只需要在方法名前加__
class Cup:
#构造函数,初始化属性值
def __init__(self,capacity,color):
#私有属性,只需要在属性名字前加__
self.__capacity=capacity
self.color=color
#私有方法,只需要在方法名前加__
def __retain_water(self):
print("杯子颜色:"+self.color+",杯子容量:"+self.__capacity+",正在装水.")
def keep_warm(self):
print("杯子颜色:"+self.color+",杯子容量:"+self.__capacity+",正在保温.")
currentCup=Cup('50ml','紫色')
#外部调用失败,因为__retain_water()方法是私有的
currentCup.__retain_water()
执行结果:
参考链接:点此链接
-
13、python 类变量带一个_和带两个__的区别
1.带_的变量:标明是一个私有变量,只用于标明,外部类还可以访问到这个变量。
2.前面带两个_,后带两个_ 的变量:标明是内置变量,外部类访问不到这个变量。
3.不带_的变量:是公共变量,外部类还可以访问到这个变量。
import uuid
class BaseTask:
_taskid = uuid.uuid1()
__taskname = 'scaning'
_pending_task = []
_running_task = []
_name = 'scaning'
jsondata = dict()
def _dictinfo(self):
self.jsondata['id'] = str(self._taskid)
self.jsondata['name'] = self._name
self.jsondata['taskqueue'] = self._pending_task
print(self.jsondata)
print(BaseTask._taskid)
print(BaseTask._pending_task)
print(BaseTask.__taskname)
print(dir(BaseTask))
a = BaseTask()
print(a._dictinfo())
执行结果:
参考链接:点此链接
-
14、解决NameError: name '__file__' is not defined的方法
方法1
import os
base_dir = os.path.dirname(os.path.realpath('__file__'))
print(base_dir)
方法2
import os
base_dir = os.getcwd()
print(base_dir)
-
15、Numpy基础计算
链接:点此链接
import networkx as nx
import matplotlib.pyplot as plt
# 创建有向图G = nx.DiGraph() #建立一个空的无向图G = nx.Graph()
G = nx.Graph()
# 有向图之间边的关系
edges = [("A", "B"), ("B", "D"), ("D", "B"), ("D", "C"), ("C", "A")]
for edge in edges:
G.add_edge(edge[0], edge[1])
nx.draw(G,with_labels=True)
plt.show()
pagerank_list = nx.pagerank(G, alpha=0.85)
print("pagerank值是:\n", pagerank_list)
参考链接:点此链接
-
17、0 or 1,1 and 0
一.或运算
1.0 or 1
结果为:1
2.1 or 0
结果为:1
3.1 or 2
结果为:1
4.2 or 1
结果为:2
5.0 or []
结果为:[]
6.[] or 0
结果为:0
二.与运算
1.0 and 1
结果为:0
2.1 and 0
结果为:0
3.1 and 2
结果为:2
4.2 and 1
结果为:1
5.' ' and 0
结果为:' '
6.0 and ' '
结果为:0
三.混合运算
1.1 < ( 2 == 2)
结果为:False 这道题就不用多说了,2==2为True,True换成数字为1,1<1明显为Flase
2.1 < 2 == 2
结果为:True
按照正常思路,比较运算优先级比等于优先级高,所以这道题先算1 < 2 为True,True为1,1不等于2,所以为Flase
但是,答案明明就是True,实际上这道题是这样算的:
1 < 2 and 2 == 2 这样一转变,是不是立马就明白了
因为逻辑运算优先级低,所以最后运算为:True and True
总结:
1.or:或运算的两边,有真则真;若都为真,则选前者;若都为假,则选后者;
2.and:与运算的两边,有假则假;若都为真,则选后者;若都为假,则选前者;
3.混合运算时,应当考虑运算符优先级的问题,当有括号时,先算括号内的运算
内容来源:点此链接
18、sorted() key详解
sorted(dict, key=dict.__getitem__, reverse=True)
1)__getitem__它只是重定向到字典,返回字典的值
class Animal:
def __init__(self, animal_list):
self.animals_name = animal_list
def __getitem__(self, index):
"Python的魔法方法__getitem__ 可以让对象实现迭代功能,这样就可以使用for...in... 来迭代该对象了"
return self.animals_name[index]
animals = Animal(["dog","cat","fish"])
for animal in animals:
print(animal)
2)itemgetter根据某个或某几个字典字段来排序列表
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号。看下面的例子
from operator import itemgetter
#itemgetter函数用于获取对象的哪些维的数据,参数为一些序号
#要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。
a=[1,2,3,4,5]
b=itemgetter(1) #定义函数b,获取对象的第1个域的值
print(b(a))
b=itemgetter(1,0) #定义函数b,获取对象的第1个域和第0个的值
print(b(a))
a = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
# 根据第二个域和第三个域进行排序
print(sorted(a, key=itemgetter(0,2)))
19、anaconda python以前版本下载地址
0).最新版本官网下载:
https://www.anaconda.com/distribution/
1)、anaconda 历史版本下载地址:
首推清华镜像,特别是公司内部网络有代理设置的。
清华镜像(国内首选): https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/
官网镜像:https://repo.continuum.io/archive/
2)、anaconda 版本与python 版本一一对应表(只限Windows)
anaconda 版本 | python 版本 | 大小 | 发布时间 |
Anaconda3-4.0.0-Windows-x86_64.exe | 3.5.1 | 345.4 MiB | 2017/1/31 1:37 |
Anaconda3-4.1.0-Windows-x86_64.exe | 3.5.1 | 351.4 MiB | 2017/1/31 1:40 |
Anaconda3-4.1.1-Windows-x86_64.exe | 3.5.2 | 352.9 MiB | 2017/1/31 1:43 |
Anaconda3-4.2.0-Windows-x86_64.exe | 3.5.2 | 391.4 MiB | 2017/1/31 1:46 |
Anaconda3-4.3.0-Windows-x86_64.exe | 3.6.0 | 421.2 MiB | 2017/2/2 9:15 |
Anaconda3-4.3.0.1-Windows-x86_64.exe | 421.2 MiB | 2017/2/4 0:33 | |
Anaconda3-4.3.1-Windows-x86_64.exe | 3.6.0 | 422.1 MiB | 2017/3/11 1:59 |
Anaconda3-4.4.0-Windows-x86_64.exe | 3.6.1 | 437.6 MiB | 2017/5/31 3:27 |
Anaconda3-5.0.0-Windows-x86_64.exe | 3.6.2 | 510.0 MiB | 2017/9/27 6:17 |
Anaconda3-5.0.1-Windows-x86_64.exe | 3.6.3 | 514.8 MiB | 2017/10/26 0:45 |
Anaconda3-5.1.0-Windows-x86_64.exe | 3.6.4 | 537.1 MiB | 2018/2/15 23:27 |
Anaconda3-5.2.0-Windows-x86_64.exe | 3.6.5 | 631.3 MiB | 2018/5/31 2:41 |
Anaconda3-5.3.0-Windows-x86_64.exe | 3.7.0 | 631.4 MiB | 2018/9/28 6:46 |
Anaconda3-5.3.1-Windows-x86_64.exe | 3.7.0 | 632.5 MiB | 2018/11/20 4:04 |
点此链接:anaconda旧版本 下载地址及与python各版本对应关系_heivy的博客-CSDN博客_anaconda 老版本
20、修改 jupyter notebook的默认文件夹位置
https://www.lizenghai.com/archives/29094.html
jupyter_notebook_config
问题:
'jupyter_notebook_config' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
解决
pip install jupyter notebook -i https://pypi.mirrors.ustc.edu.cn/simple
21、pandas读取Excel将某字段CODE赋予文本值
data_after=pd.read_excel(excel_dir,sheet_name='产品',converters ={'code':str})