放假没事一边到公园玩,一边看看这本书。我是很推荐这本书的,不少儿时耳熟能详的诗歌,这里又重温了一下,而且放到了当时的背景和诗人境遇来看,让人有了另一层感悟。
陈子昂的复古,王昌龄的塞外,孟浩然的田园,王维的诗中有画,李白的豪放,一首首诗串起了中华文化瑰丽的画卷。作为程序员,忍不住就想做点什么,先第一步:把唐诗三百首下载下欣赏。

于是花了几个小时写了点python代码,也很简单,就是读取诗目录,然后循环读取诗的内容,并写入本地文件。50行代码,用了requests读网站,BeautifulSoup做解析,目录和文件生成写入,然后一点正则表达式做文本处理。最后结果如下:



代码如下,copy后就可以python运行了。
import requests
import os
import time
import re
from bs4 import BeautifulSoup
def write_poem(url,author,title) :
if(not os.path.exists('唐诗三百首/'+author)) :
os.makedirs('唐诗三百首/'+author)
file_path='唐诗三百首/'+author+'/'+title+'.txt'
if os.path.exists(file_path) : #有文件就不用再读了,便于任务恢复
return
time.sleep(5)
print('get url:'+url)
try:
r=requests.get(url,timeout=5)
except :
print("connect error")
return
print('geted url:'+url)
html=r.text
soup=BeautifulSoup(html)
content=soup.find('div',attrs={'class':'contson'}).text
content=re.sub("\(.*?\)", '', content)
content=content.replace('。','。\n')
with open(file_path,'w') as f:
f.write(title+"\n")
f.write(author+"\n")
f.write(content)
print('writed:'+title)
#write_poem('https://so.gushiwen.org/shiwenv_43c5b73dbd73.aspx','陈陶','陇西行')
def write_poems() :
url='http://www.gushiwen.org/gushi/tangshi.aspx'
r=requests.get(url,timeout=10)
html=r.text
soup=BeautifulSoup(html)
catalog_list=soup.find_all('div',attrs={'class':'typecont'})
for catalog in catalog_list :
poems=catalog.find_all('span')
for poem in poems :
url=poem.find('a').get('href')
p=poem.text.split('(')
if(len(p)!=2) :
break
title=p[0]
author=p[1][:-1]
print("Fetch:"+title+"-"+author+"-"+url)
write_poem(url,author,title)
write_poems()
网友评论