2、待读取文件
是以":"作为分隔符的数据,每一行以回车结束。此文件为XXX.train
3、读取每一句中的汉字
1234567891011...file_train = os.path.join(rootDir,"data/train/rg_train_"+modle_date+"_"+aiscene+".train")with open(file_train, 'r')as fp: textlist = fp.readlines() for text in textlist: if ":" in text: L4ID = text.split(":")[-2] Msg = text.split(":")[-1] if query_start == Msg.strip("\n"): print("Msg is in train:",Msg)...
代码中先获取文件,然后读取每一行,然后以":"作为分隔符。(-1代表倒数第一个,-2代表倒数第二个)
不管是txt文件还是xml文件还是其他的,都可以用这种方法来批量替换文件中字符串:
1234567891011121314151617# -*- coding:utf-8 -*-__author__ = 'ShawDa' import glob xmls = glob.glob('xml_files/*.xml')for one_xml in xmls: print(one_xml) f = open(one_xml, 'r+', encoding='utf-8') all_the_lines = f.readlines() f.seek(0) f.truncate() for line in all_the_lines: line = line.replace('dog', 'pig') line = line.replace('cat', 'bike') f.write(line) f.close()