Python中常用的文本处理操作

#读文本

with open('abc.txt' , 'r') as f:

    txt = f.readlines()

#分割字符串

string.split(' ') / split('.') / split('_') / split('/')    #分割符分别是空格/点/下划线/斜杠

s1,s2,s3 = string.split('.' , 2)    #分割两次,并将这三个部分保存为s1,s2,s3

string.split('.' , 2)[1]    #分割两次,并取序列(从0计)为1的项

 举例:

 for line in txt:

     words = line.split(' ')

     注:若是每行一个,可以加入消除\n影响的操作 imgpath = imgpath.split('\n')[0]

     img_file_name = './data/' + words[0] + '.jpg'

#扩展字符串

for line in txt:

    cls_list.append( [words[0],label,roi] )

#翻转列表

a.reverse()或a[::-1]

#写文本

f = open( os.path.join(save_dir, 'abc.txt'), 'w')

f.write( '12/positive/%s'%p_idx + '1' + '%.2f %.2f %.2f %.2f\n'%(x1,y1,x2,y2) )

f.close()

#生成随机数

import random

random.choice( [-1,0,1] )

random.choice( range(100) )

 或者
import numpy.random as npr
npr.choice( 100, size=80, replace=False )    #从range(100)中随机产生80(不写就默认为1)个数,且不重复

你可能感兴趣的:(Python中常用的文本处理操作)