python常用方法
1.字符串
1.1 split()
描述
split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
语法
str.split(str=”“, num=string.count(str))
参数
str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num – 分割次数。
返回值
返回分割后的字符串列表。
str = 'This is string example...wow!!!'
print (str.split())
print (str.split('i', 1))
print (str.split('w'))
1.2 strip()
描述
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
语法
str.strip([chars]);
参数
chars – 移除字符串头尾指定的字符序列。
返回值
返回移除字符串头尾指定的字符序列生成的新字符串。
str = '****This is **string** example...wow!!!***'
print (str.strip('*'))
# 下面代码演示了只要头尾包含有指定字符序列中的字符就删除(顺序可不一致)
str = '123abcabc321'
print (str.strip('21'))
1.3 len()
描述
Python len() 方法返回对象(字符、列表、元组等)长度或项目个数。
语法
len( s )
参数
s – 对象。
返回值
返回对象长度。
print (len(str))
str = '****This is **string** example...wow!!!***'
print (len(str))
list = [1, 2, 3, 4]
print (len(list))
2.文件读写
2.1 txt文件
1 简单处理文件:
context=”hello,world”
f=file(“hello.txt”,’w’)
f.write(context);
f.close()
2 读取文件可以使用readline()函数、readlines()函数和read函数。
3 写入文件可以使用write()、writelines()函数
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'python3 file常用方法'
# 打开文件
# 执行完自动close,避免忘记关闭文件导致资源的占用
with open('hello.txt', 'w', encoding = 'utf-8') as f:
# 文件的写
# file.write(str):将字符串写入文件,返回的是写入的字符长度。
f.write('hello, world')
f.write('\n')
str = 'hello, world'
f.write(str)
# 文件的读
# file.readlines([sizeint]):读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行
with open('hello.txt', 'r', encoding = 'utf-8') as f:
# for line in f.readlines():
# print ('读取的数据为: %s' %(line))
for line in f.readlines():
line = line.strip() # 去掉每行头尾空白
print ('读取的数据为: %s' %(line))
# file.readline([size]):读取整行,包括 "\n" 字符。
with open('hello.txt', 'r', encoding = 'utf-8') as f:
line = f.readline()
print ('读取第一行 %s' %(line))
line = f.readline(5)
print ('读取的字符串为 %s' %(line))
2.2 csv文件的读取与存储
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'csv文件的读取与存储'
import csv
# 网上获取csv文件
dataSet = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/ionosphere/ionosphere.data")
# 存储csv文件到本地
dataSet.to_csv('dataSet.csv')
# 从本地读取csv文件
csv_file = csv.reader(open("dataSet.csv", "r"))
# 打印输出
print (csv_file)
for i in csv_file: #打印每行数据
print(i)
将csv文件转成矩阵,可以用上面读取每行再存到数组的方式,但是比较麻烦。可以用pandas直接将csv文件内的数据转成矩阵的形式。代码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'csv文件的读取与存储'
import csv
import pandas as pd
# 网上获取csv文件
dataSet = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/ionosphere/ionosphere.data")
# 存储csv文件到本地
dataSet.to_csv('dataSet.csv')
# 从本地读取csv文件-使用Pandas方法
dataSet = pd.read_csv("dataSet.csv")
# 将pandas格式的framework转成矩阵
dataSet = dataSet.values
print (dataSet) # 测试
使用python pandas读取csv文件的指定列:
# usecols参数表示读取的是第几列,注意从0开始
# 可以写多个,如usecols = [1, 2, 3]等
labels = pd.read_csv("dataSet.csv", usecols = [35])
将矩阵保存为csv文件:
numpy.savetxt('new.csv', my_matrix, delimiter = ',')
3.python字符串连接
方法1:通过加号(+)操作符连接(使用简单,连接的字符串多的情况下效率低)
website = 'www.' + 'google' + '.com'
方法2:join方法(使用略复杂,对多个字符连接时效率高,对List字符拼接时首选)
listStr = ['python', 'tab', '.com']
website = ''.join(listStr)
方法3:替换(字符串格式化,常用,推荐使用)
website = '%s%s%s' % ('python', 'tab', '.com')
参考:https://www.cnblogs.com/chenjingyi/p/5741901.html
4.python len()函数
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
X = np.zeros(shape=(3,4))
print(len(X)) # >>> 3
print(len(X[0])) # >>> 4