python處理文件內容的正確姿勢該怎樣?
問題描述
大神們:
我想把htm文件中的第一個<link到第二個<link之間的所有內容另存為一個htm該怎么寫比較簡潔。
<meta http-equiv='X-UA-Compatible' content='IE=edge'><link rel='prefetch' ><meta name='application-name' content='Python.org'><meta name='msapplication-tooltip' content='The official home of the Python Programming Language'><meta name='apple-mobile-web-app-title' content='Python.org'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='viewport' content='width=device-width, initial-scale=1.0'><meta name='HandheldFriendly' content='True'><meta name='format-detection' content='telephone=no'><meta http-equiv='cleartype' content='on'><meta http-equiv='imagetoolbar' content='false'><script type='text/javascript' async='' src='https://ssl.google-analytics.com/ga.js'></script><script src='http://www.lshqa.cn/wenda/Welcome to Python.org_files/modernizr.js.下載'></script><style type='text/css' adt='123'></style><link href='http://www.lshqa.cn/wenda/Welcome to Python.org_files/style.css' rel='stylesheet' type='text/css'><link href='http://www.lshqa.cn/wenda/Welcome to Python.org_files/mq.css' rel='stylesheet' type='text/css' media='not print, braille, embossed, speech, tty'>
提取的內容應該是:
<link rel='prefetch' ><meta name='application-name' content='Python.org'><meta name='msapplication-tooltip' content='The official home of the Python Programming Language'><meta name='apple-mobile-web-app-title' content='Python.org'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='viewport' content='width=device-width, initial-scale=1.0'><meta name='HandheldFriendly' content='True'><meta name='format-detection' content='telephone=no'><meta http-equiv='cleartype' content='on'><meta http-equiv='imagetoolbar' content='false'><script type='text/javascript' async='' src='https://ssl.google-analytics.com/ga.js'></script><script src='http://www.lshqa.cn/wenda/Welcome to Python.org_files/modernizr.js.下載'></script><style type='text/css' adt='123'></style><link
問題解答
回答1:import retext = ''with open('read.html', 'r') as rf: text = rf.read() pattern = r'<link[sS]*?<link'results = re.findall(pattern, text)if results: r = results[0] with open('write.html', 'w') as wf:wf.write(r) ================================================with open('read.html', 'r') as rf: with open('write.html', 'w') as wf:num = 0for line in rf.readlines(): if line.startswith('<link'):num += 1continue if num == 2:break wf.writelines(line)
相關文章:
1. docker-machine添加一個已有的docker主機問題2. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?3. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””4. css - 求推薦適用于vue2的框架 像bootstrap這種類型的5. Span標簽6. SessionNotFoundException:會話ID為null。調用quit()后使用WebDriver嗎?(硒)7. angular.js使用$resource服務把數據存入mongodb的問題。8. css - 關于div自適應問題,大家看圖吧,說不清9. redis啟動有問題?10. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?
