Python 文本处理 论语

1.问题描述:请编写程序,提取《论语》文档中所有原文内容,输出保存到“论语-提取版.txt”文件。输出文件格式要求:去掉文章中原文部分每行行首空格及如“1.11”等的数字标志,行尾无空格、无空行。参考格式如下(原文中括号及内部数字是对应源文件中注释项的标记):

 

 1 j=7
 2 k=0
 3 a=0
 4 b=0
 5 l=[]
 6 content=[]
 7 
 8 try:
 9     with open(r'C:\Users\DELL\Desktop\论语.txt','r',encoding='utf-8') as file1:
10         for line in file1:
11             newline=line
12             if newline[2:5] in [str(m)+'·'+str(n) for m in range(1,25) for n in range(1,25)]\
13                     or newline[2:6] in [str(m)+'·'+str(n) for m in range(1,25) for n in range(1,25)]\
14                     or newline[2:7] in [str(m)+'·'+str(n) for m in range(1,25) for n in range(1,25)]\
15                     or newline[2:8] in [str(m)+'·'+str(n) for m in range(1,25) for n in range(1,25)]:
16                 for p in [str(m)+'·'+str(n) for m in range(45,0,-1) for n in range(45,0,-1)]:
17                     if p in newline[0:9]:
18                         newline2=newline.replace(p,'')
19                         content.append(newline2)
20                         break
21 
22             else:
23                 content.append(newline)
24 
25 
26     with open(r'C:\Users\DELL\Desktop\论语改2.txt','w',encoding='utf-8') as file2:
27         for i in range(len(content)):
28 
29             if '【原文】' in content[i] and i>=b:
30 
31                 a=i
32                 k=i
33 
34                 while k!=0:
35                     if '】' in content[k+1]:
36                         b=k+1
37                         l.append([a,b])
38                         break
39                     else:
40                         k+=1
41         for m,n in l:
42             for line in content[m+1:n-1]:
43                 file2.write(line)
44 
45 
46 
47 
48 
49 except Exception as t:
50     print(t)

 

上一篇:JAVA视频链接


下一篇:XML解析的四种方法 建议使用demo4j解析 测试可以用