python学习笔记

Python

Python 官网: http://https://www.python.org
Pychorm 官网: http://www.jetbrains.com/pycharm

@(学习笔记)[Python]

Python的初始配置

windows

1. python的多版本安装
  • 安装从官网下载的安装包
  • 进入第一个版本安装目录 给pychon.exe改名, 如pychon2.exe, 再进入第二个版本安装目录 给python.exe改名, 如python3.exe
  • 将上面两个路径添加到系统环境变量及Scripts路径也添加到环境变量(有些电脑需要重启电脑才能生效)
2. python常用第三方库的安装
  • python2 -m pip install
  • python3 -m pip install numpy
  • pip install --upgrade ... 软件包升级
  • pip install ipython 安装ipython
  • pip install seaborn 安装数据可视化模块
  • pip install scrapy 安装爬虫框架
  • pip install jupyter notebook 启动notebook jupyter notebook
  • 附上python常用第三方库网址: http://www.lfd.uci.edu/~gohlke/pythonlibs/
3. pycharm使用多版本python的配置
  • 打开pychorm
  • 依次点击file-> Settings-> Project:python-> Project Interpreterl
  • 选择要使用的python版本号
4. 将py文件打成exe
  • pip install pyinstaller
  • pyinstaller -F decode.py
5.调用so
/***gcc -o libpycall.so -shared -fPIC pycall.c*/  
#include <stdio.h>  
#include <stdlib.h> 
extern "C"
{ 
    int foo(int a, int b)  
    {  
      printf("you input %d and %d\n", a, b);  
      return a+b;  
    } 
} 
  • gcc -o libpycall.so -shared pycall.c
import ctypes

ll = ctypes.cdll.LoadLibrary
lib = ll("libpycall.so")
print(lib)
k = lib.foo(1, 3)
print(k)
print( '***finish***' )

常用函数或命令

  • 调用windows命令dir
cmd_res = os.popen('dir').read()
print (cmd_res)
  • 判断数据是否是字符串
st = 'bingwuss'
st.isdigit()
    or
type(st) is str   
  • 判断是否是数字(可以是字符串形式)
s = '12'
s.isdigit()
or
s = 3
s.isdigit()    

序列

  • com(seq1, seq2) 比较两个序列
  • len(seq) 求取序列的长度
  • max(seq) 求取序列中元素最大值
  • min(seq) 求取序列中元素最小值
  • enumerate(seq) 获取列表每个数据的偏移量和值 返回一个生成器对象
tuple(元组)
  • tuple(list)将列表转换为元组
list(列表)
  • list.append(obj) 在列表末尾添加新的对象
  • list.count(obj) 统计某个元素在列表中出现的次数
  • list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)返回值为None
  • list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
  • list.insert(index, obj) 将对象插入列表
  • list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
  • list.remove(obj) 移除列表中某个值的第一个匹配项
  • list.reverse() 反向列表中元素
  • list.sort([func]) 对原列表进行排序
dict(字典)
  • dict.clear() 删除字典内所有元素
  • dict.copy() 返回一个字典的浅复制
  • dict.fromkeys(seq, val) 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
  • dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值
  • dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
  • dict.has_key(key) 如果键在字典dict里返回true,否则返回false
  • dict.items() 以列表返回可遍历的(键, 值) 元组数组
  • dict.keys() 以列表返回一个字典所有的键
  • dict.values() 以列表返回字典中的所有值
  • dict.update(dict2) 把字典dict2的键/值对更新添加到dict里
  • dict.pop(key, default) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
  • dict.popitem() 随机返回并删除字典中的一对键和值。

字符串

常用命令
  • str.capitalize() 将字符串的第一个字符转换为大写
string = 'hello World'
print(string.capitalize())
  • swapcase() 将字符串中大写转换为小写小写转换为大写
string = 'hello World'
print(string.swapcase())
  • str.upper() 转换字符串中的小写字母为大写
string = 'hello World'
print(string.upper())
  • str.lower() 转换字符串中的大写字母为小写
string = 'hello World'
print(string.lower())
  • str.center(width, fillchar) 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格
string = 'hello World'
print(string.center(20, '*'))
  • str.ljust(width, fillchar) 返回一个原字符串左对齐,并使用fillchar(默认空格)填充至长度 width新字符串
string = 'hello World'
print(string.ljust(20, '*'))
  • str.rjust(width, fillchar) 返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width新字符串
string = 'hello World'
print(string.rjust(20, '*'))
  • str.zfill (width) 返回长度为 width 的字符串,原字符串右对齐,前面填充0
string = 'hello World'
print(string.zfill(20)
  • str.lstrip(chars=None) 截掉字符串 左边的空格指定字符
string = ' hello World'
print(string.lstrip ('hel'))
  • str.rstrip(chars=None) 删除字符串 末尾的空格指定字符
string = 'hello World'
print(string.rstrip ('rld'))
  • strip(chars=None) 在字符串上执行 lstrip()rstrip()
string = '22hello World2'
print(string.strip ('2'))
  • str.count(str, beg= 0,end=len(string)) 返回 strstring 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
string = '22hello World2'
print(string.count('l', 2, -1))
  • str.split(str="", num=string.count(str)) num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅使用 numstr截取字符串
string = 'hello World'
print(string.split('l', 3))
  • str.splitlines([keepends]) 按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符
  • bytes.decode(encoding="utf-8", errors="strict") Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回
  • str.encode(encoding='UTF-8',errors='strict')encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是‘ignore’或者‘replace’
  • str.endswith(str='', beg=0, end=len(string)) 检查字符串是否以 str 结束,如果beg 或者 end 指定则检查指定的范围内是否以 str 结束,如果是,返回 True,否则返回 False
string = 'hello World'
print(string.endswith('o', 0, 4))
  • str.expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8
  • str.find(str='', beg=0 end=len(string)) 检测 str 是否包含在字符串中 中,如果 begend 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
string = 'helloWorld'
print(string.find('o', 0, 6))
  • str.rfind(str='', beg=0,end=len(string)) 类似于 find()函数,不过是从右边开始查找
string = 'helloWorld'
print(string.rfind('o', 0, 6))
  • str.index(str='', beg=0, end=len(string))find()方法一样,只不过如果str不在字符串中会报一个异常
string = 'helloWorld'
print(string.index('o', 0, 6))
  • str.rindex( str='', beg=0, end=len(string)) 类似于 index(),不过是从右边开始
string = 'helloWorld'
print(string.rindex('o', 0, 6))
  • str.isalnum() 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
string = 'hello2World'
print(string.isalnum())
  • str.isalpha() 如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False
string = 'helloWorld'
print(string.isalpha())
  • str.isdigit() 如果字符串只包含数字则返回 True 否则返回 False
string = '2244'
print(string.isdigit())
  • str.islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
string = 'hello world'
print(string.islower())
  • str.isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
sring = 'HELLO WORLD'
print(string.isupper())
  • str.isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False
string = 'Ⅷ'
print(string.isnumeric())
  • str.isspace() 如果字符串中只包含空白,则返回 True,否则返回 False
string =  '  '
print(string.isspace())
  • str.istitle() 如果字符串是标题化的(见 title())则返回 True,否则返回 False
string =  'Hello World'
print(string.istitle())
  • str.title() 返回“标题化”字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
string =  'hello world'
print(string.title())
  • str.maketrans() 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标
  • str.translate(table, deletechars="") 根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))

以上实例输出结果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
  • max(str) 返回字符串 str最大的字母
  • min(str) 返回字符串 str最小的字母
  • str.replace(old, new, count=None) 把将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次
string =  'hello world'
print(string.replace('l', 'k', 2))
  • str.startswith(str='', start=None, end=None) 检查字符串是否是以 str开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查
string =  'hello world'
print(string.startswith('he'))
  • str.endswith(str='', start=None, end=None) 检查字符串是否是以 str结尾,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查
string =  'hello world'
print(string.startswith('ld'))
  • str.isdecimal() 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false
string =  '3241'
print(string.isnumeric())

文件操作

  • open() 打开文件

  • readline() 读取一行

  • readlines() 读取所有行 放到一个列表里 适合读小文件
  • read() 读取剩下的内容 文件大时不要用
  • write() 像文件写入土内容
  • close() 关闭文件
file = open('file', 'a', encoding = 'utf-8')
file.close()

正则

修饰符
修饰符 描述
re.I    使匹配对大小写不敏感
re.L    做本地化识别(locale-aware)匹配
re.M    多行匹配,影响 ^ 和 $
re.S    使 . 匹配包括换行在内的所有字符
re.U    根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X    该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解
常用函数
  • re.compile(pattern, flags=0) 将正则表达式编译成pattern对象
import re

# 将正则表达式编译成Pattern对象
pattern = re.compile(r'hello')

# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
match = pattern.match('hello world!')

if match:
    # 使用Match获得分组信息
    print match.group()

### 输出 ###
# hello
  • re.match(pattern, string, flags=0) 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
import re

print(re.match(r'www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.match(r'com', 'www.runoob.com'))         # 不在起始位置匹配

line = "Cats are smarter than dogs"
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M | re.I)
print("matchObj.group()  : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.group(2) : ", matchObj.group(2))

### 输出 ###
# (0, 3)
# None
# matchObj.group() :  Cats are smarter than dogs
# matchObj.group(1) :  Cats
# matchObj.group(2) :  smarter
  • re.search(pattern, string, flags=0) 扫描整个字符串并返回第一个成功的匹配
  • re.sub(pattern, repl, string, count=0, flags=0) 替换字符串中的匹配项
import re

phone = "2004-959-559 # 这是一个国外电话号码"

# 删除字符串中的 Python注释 
num = re.sub(r'#.*$', "", phone)
print "电话号码是: ", num

# 删除非数字(-)的字符串 
num = re.sub(r'\D', "", phone)
print "电话号码是 : ", num
  • re.split(pattern, string, maxsplit=0, flags=0)按照能够匹配的子串将string分割后返回列表, 用于指定最大分割次数,不指定将全部分割
import re

p = re.compile(r'\d+')
print (p.split('one1two2three3four4'))

### output ###
# ['one', 'two', 'three', 'four', '']
  • re.findall(self, path, namespaces=None) 以列表形式返回全部能匹配的子串
import re

p = re.compile(r'\d+')
print (p.findall('one1two2three3four4'))

### output ###
# ['1', '2', '3', '4']
  • finditer(self, string, pos=0, endpos=-1) 返回一个顺序访问每一个匹配结果(Match对象)的迭代器
import re

p = re.compile(r'\d+')
for m in p.finditer('one1two2three3four4'):
    print(m.group())

### output ###
# 1
# 2
# 3
# 4
匹配实例
实例  描述
[Pp]ython        匹配 "Python" 或 "python"
rub[ye]          匹配 "ruby" 或 "rube"
[aeiou]          匹配中括号内的任意一个字母
[0-9]            匹配任何数字。类似于 [0123456789]
[a-z]            匹配任何小写字母
[A-Z]            匹配任何大写字母
[a-zA-Z0-9]      匹配任何字母及数字
[^aeiou]         除了aeiou字母以外的所有字符
[^0-9]           匹配除了数字外的字符
匹配语法

函数

  • __init__(self, ...) 构造函数
  • __del__(self) 析构函数
装饰器

字符编码

  • sys.getdefaultencoding() 获得编码格式

编码格式转换

panada

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print (df)
print (df.loc['d'])
print (df.iloc[1])

'''

'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值