题注
我是学Perl出生,perl在处理有些文本时是,通过判断hash字典,判断特殊key和其值是否存在,然后在值后面附加,是非常方便的。
但python比较严谨,直接这样用,会报错KeyError:
这时如果想要和Perl一样,使用该方式,进行文本信息的归类,那么可以利用
try:
except KeyError:
结构来进行操作。
实现入perl中同样的效果。
善用字典
dict = {}
try:
if dict[id]:
dict[id] = dict[id] + "//" + want_info
except KeyError:
dict[id] = want_info
通过这样的方式,可以在for一个文本时,把不同行里,id一样,但附加信息不一的内容,整合到字典中,然后之后单独写到相应的输出文档之中即可。
python 文本处理需掌握
普通文本txt格式的操作,打开等,标准套路。
with open(filein,'r',encoding='utf-8')as f:
lines = f.readlines()
for line in lines:
line = line.strip('\n')
info = line.split('\t')
with open(fileout, 'w', encoding='utf-8')as ww:
out = 'Drugname' + '\t' + 'NCIDS:Phase:Status:Literature' + '\t' + 'Targets' + '\n'
ww.write(str(out))
with open(fileout, 'a', encoding='utf-8')as ww:
outnr = line + '\t' + drugaa + '\n'
ww.write(str(outnr))
学习使用pandas,对excel等内容进行操作。
import pandas as pd
excel_path = 'E:\\haxqd\\myscript\\clin_drug_id_info_targets_and_AA_output.xlsx'
d = pd.read_excel(excel_path,header=0) # header表示取第一行作为列名
…………
writer = pd.ExcelWriter('E:\\haxqd\\myscript\\clin_drug_id_info_targets_and_AA_addinfo_all_info.xlsx')
d.to_excel(writer,'Sheet1',index_label=None,index = False)
writer.save()
PS:
比起try:except: 处理字典,字典有一个get()方法更方便一些,可以避免错误,有的话返回值,没有返回”None”