Python二級-文本處理-論語


1.問題描述:請編寫程序,提取《論語》文檔中所有原文內容,輸出保存到“論語-提取版.txt”文件。輸出文件格式要求:去掉文章中原文部分每行行首空格及如“1.11”等的數字標志,行尾無空格、無空行。參考格式如下(原文中括號及內部數字是對應源文件中注釋項的標記):

2.請編寫程序,在“論語-提取版.txt”基礎上,進一步去掉每行文字中所有括號及其內部數字,保存為“論文-原文.txt”文件。

 論語下載地址

問題一:

 1 k=0
 2 a=0
 3 b=0
 4 l=[]
 5 content=[]
 6 
 7 try:#異常捕捉框架  8     with open(r'C:\Users\DELL\Desktop\論語文本\論語.txt','r',encoding='utf-8') as file1:
 9         for line in file1:#逐行遍歷文本 10             newline=line#單行處理預留 11             if newline[2:5] in [str(m)+'·'+str(n) for m in range(1,25) for n in range(1,25)]\
12                     or newline[2:6] in [str(m)+'·'+str(n) for m in range(1,25) for n in range(1,25)]\
13                     or newline[2:7] in [str(m)+'·'+str(n) for m in range(1,25) for n in range(1,25)]:#判斷首部數字標識 14                 for p in [str(m)+'·'+str(n) for m in range(45,0,-1) for n in range(45,0,-1)]:#消除首部標識,並加入列表content 15                     if p in newline[0:9]:
16                         newline2=newline.replace(p,'')
17                         content.append(newline2)
18                         break
19 
20             else:#無標識則直接加入content 21                 content.append(newline)
22 
23     with open(r'C:\Users\DELL\Desktop\論語文本\論語改2.txt','w',encoding='utf-8') as file2:
24         for i in range(len(content)):#進行標識起點的識別 25 
26             if '【原文】' in content[i] and i>=b:
27 
28                 a=i
29                 k=i
30 
31                 while k!=0:
32                     if '' in content[k+1]:#判斷內容是否屬於標識終點,是則跳出循環進行標識起點的判斷 33                         b=k+1
34                         l.append([a,b])
35                         break
36                     else:
37                         k+=1#將k的標識加一,進行下一行的判斷
38         for m,n in l:#遍歷標識起點和終點 39             for line in content[m+2:n-1]:#將標識起點和終點的原文部分直接逐行處理並寫入文件 40                 if line=='\n':
41                     continue
42                 else:
43                     file2.write(line + '\n')
44 
45 
46 except Exception as t:
47     print(t)

 問題二:

1 try:
2     with open(r'C:\Users\DELL\Desktop\論語文本\論語改2.txt','r',encoding='utf-8') as file3,open(r'C:\Users\DELL\Desktop\論語文本\論語改8.txt', 'w', encoding='utf-8') as file4:
3         for line in file3:
4             for i in range(0,30):#
5                 line=line.replace(f'({i})',"")#由於.replace方法具有生成新對象,故需要重新定義 6             file4.write(line)#將處理好的每行字符串文本寫入文件8 7 except Exception as t:
8     print(t)

 

若有不當之處,請各位不吝賜教。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM