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.piao2010.com/wenda/Welcome to Python.org_files/modernizr.js.下載'></script><style type='text/css' adt='123'></style><link href='http://www.piao2010.com/wenda/Welcome to Python.org_files/style.css' rel='stylesheet' type='text/css'><link href='http://www.piao2010.com/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.piao2010.com/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. 求大神支招,php怎么操作在一個html文件的<head>標記內添加內容?2. 安裝了“PHP工具箱”,但只能以“游客”身份登錄3. 老師們php,插入數據庫mysql,都是空的,要怎么解決4. 怎么php怎么通過數組顯示sql查詢結果呢,查詢結果有多條,如圖。5. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現存在即更新應該使用哪個標簽?6. 致命錯誤: Class ’appfacadeTest’ not found7. 在應用配置文件 app.php 中找不到’route_check_cache’配置項8. PHP類屬性聲明?9. php點贊一天一次怎么實現10. phpstady在win10上運行
