# -*- coding: utf-8 -*- """ Created on Wed Nov 21 10:47:49 2018 @author: Youly """ def Separate_items_answers(path): """ test paper have 3 types:1.answer is at the final sign:######################### 2.answer is in the paper 3.no answer sign:************************************ :param path:where your txt_file is :return:list:items;list:answers << one line content is one element """ items = [] answers = [] try: with open(path,'r',encoding='utf-8') as f: # print('txt的所有内容: %s' % f.read()) content = f.readlines() # print(content) answers_start = 0 if '####################' in ''.join(content): # if txt has no ##############,has no answers or answers among test_paper,do not deal with this kind of txt for i,line in enumerate(content): Nline = line.replace(' ','').replace('#','') if line == '' or line.rstrip() == '': # \n # items.append('') pass elif Nline.rstrip() != '': # not :################### not \n items.append(line) elif '####################' in line and Nline.rstrip() == '': # only get data before ################ answers_start = i+1 break for line in content[answers_start:]: Nline = line.replace(' ', '').replace('#', '') if line == '' or line.rstrip() == '': # \n answers.append('') elif Nline.rstrip() != '': # not :################### not \n answers.append(line) elif '*******************' in ''.join(content): # no answer for i,line in enumerate(content): Nline = line.replace(' ', '').replace('#', '') if line == '' or line.rstrip() == '': # \n # items.append('') pass elif line.rstrip() != '': # not :################### not \n items.append(line) elif '*************************' in line and Nline.rstrip() == '': # only get data before ################ answers_start = i+1 break return items, answers except: print('txt读取失败!') if __name__ == '__main__': items, ans = Separate_items_answers(r'./test_paper.txt')