여러 줄을 제거해야하는 곳에 여러 개의 HTML 파일이 있습니다.파일에서 여러 줄을 제거하십시오.
제거해야하는 줄에는 스크립트 태그를 제외하고 처음과 끝에 키워드가 없지만이 파일에서 모든 스크립트 태그를 제거하지 않으려합니다.
내가 제거하는 데 필요한 HTML 부분의 예 : 어떻게하면
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
당신이 그것을 할 수 있다고 생각하고 있습니까?
업데이트 나는 아래 @ARJMP 솔루션에 일부 수정을했다,하지만 정규식에 분석 태그를 제거하지 않고 같은 파일을 다시 반환합니다.
정규식은 https://regex101.com/r/rWLZRD/1
@ARJMP 왜 정규식이 차감되지가 맞습니까? 정규식이이 문제를 해결하는 데 사용할 수 있습니다 당신의 아주 간단한 사용 사례 고려,이 작업을 수행하는 가장 좋은 방법은 아니지만
import re
from collections import defaultdict
ga_re = r"<script type=\"text\/javascript\">\s+var _gaq = _gaq .*</script>" # our regex to subtract google analytics script
file_texts = defaultdict(str) # Temp store for file text
file_paths = ['index.html'] # list of files you want to run
for file_path in file_paths:
with open(file_path, mode='r+') as fin:
# Extract text from file
file_text = ''.join(fin.readlines())
file_texts[file_path] = file_text
# Write to backup file
with open('{}.backup'.format(file_path), mode='w+') as fbackup:
fbackup.write(file_text)
with open(file_path, mode='w+') as fout:
# Perform regex sub and write to file
file_text = file_texts[file_path]
file_text_result = re.sub(ga_re, '', file_text, re.DOTALL)
fout.write(file_text_result)
다른 방법으로 어떤 선을 제거해야하는지 설명해 주시겠습니까? 예를 들어 잘 적용될 수 있습니까? – mattjegan
삭제하려는 선을 어떻게 구체적으로 선택 하시겠습니까? 이미 그것에 대해 어떻게 생각해 봤습니까? – SCB
[Beautiful Soup] (https://www.crummy.com/software/BeautifulSoup/bs4/doc/)와 같은 HTML 작업 도구를 사용하고 싶을 것입니다. – Ryan