Python으로 HTML 파일에서 문자 계산

Oct 13 2020

방금 pythonchallenge.com에서 파이썬 챌린지 레벨 2를 완료했고 파이썬을 배우는 중이 니 저와 제가 저지른 어리석은 실수를 참아주세요.

내 코드에서 더 잘할 수 있었던 것에 대한 피드백을 찾고 있습니다. 구체적으로 두 가지 영역 :

  • HTML 파일의 주석 섹션을 더 쉽게 식별 할 수있는 방법은 무엇입니까? 나는 주석의 끝 (또는 기술적으로 시작하지만 끝부터 계산)을 찾아내는 비트 어라운드-더-부시 방법을 사용하고 내가 인식하고 예상 할 수있는 추가 문자 (추가 "->"및 "-"). 계산할 새 문자열에 넣을 수 있도록이 주석을 더 잘 찾은 조건은 무엇입니까?

이것이 내가 쓴 것입니다.

from collections import Counter
import requests

page = requests.get('http://www.pythonchallenge.com/pc/def/ocr.html')

pagetext = ""
pagetext = (page.text)
#find out what number we are going back to

i = 1
x = 4
testchar = ""
testcharstring = ""


while x == 4:
    testcharstring = pagetext[-i:]
    testchar = testcharstring[0]
    if testchar == "-":
        testcharstring = pagetext[-(i+1)]
        testchar = testcharstring[0]
        if testchar == "-":
            testcharstring = pagetext[-(i+2)]
            testchar = testcharstring[0]
            if testchar == "!":
                testcharstring = pagetext[-(i+3)]
                testchar = testcharstring[0]
                if testchar == "<":
                    x = 3
            else:
                i += 1
                x = 4
        else:
            i += 1
            x = 4
    else:
        i += 1
print(i)

newstring = pagetext[-i:]

charcount = Counter(newstring)

print(charcount)

그리고 이것은 소스 HTML입니다.

<html>
<head>
  <title>ocr</title>
  <link rel="stylesheet" type="text/css" href="../style.css">
</head>
<body>
<center><img src="ocr.jpg">
<br><font color="#c03000">
recognize the characters. maybe they are in the book, <br>but MAYBE they 
are in the page source.</center>

<br>
<br>
<br>

<font size="-1" color="gold">
General tips:
<li>Use the hints. They are helpful, most of the times.</li>
<li>Investigate the data given to you.</li>
<li>Avoid looking for spoilers.</li>
<br>
Forums: <a href="http://www.pythonchallenge.com/forums"/>Python Challenge Forums</a>, 
read before you post.
<br>
IRC: irc.freenode.net #pythonchallenge
<br><br>
To see the solutions to the previous level, replace pc with pcc, i.e. go 
to: http://www.pythonchallenge.com/pcc/def/ocr.html

</body>
</html>

<!--
find rare characters in the mess below:
-->

<!--

수천 개의 문자가 이어지고 주석은 '->'로 끝납니다.

답변

2 fartgeek Oct 13 2020 at 20:36

나는 논평 할만한 평판이 충분하지 않기 때문에 대답을해야한다. 사용하기 어색해 보입니다.

    while x == 4:

그리고

    x = 3

루프에서 벗어나고 싶을 때마다. 하는 것이 더 좋아 보인다

    while True:

루프에서 벗어나고 싶을 때

    break

건배!

1 AJNeufeld Oct 14 2020 at 05:51

중복 코드

pagetext = ""
pagetext = (page.text)

첫 번째 줄은에 빈 문자열을 할당합니다 pagetext. 두 번째 줄은 이미있는 내용을 무시 pagetext하고 변수에 다른 값을 할당합니다.

왜 첫 번째 진술을 귀찮게합니까? 단순히 코드를 더 길고 느리며 이해하기 어렵게 만듭니다.

(...)주위를 괴롭히는가 page.text? 그들은 또한 어떤 목적도 제공하지 않습니다.

변수 이름

같은 변수 i는 양날의 검입니다. 루프 인덱스로 사용하고 루프가 종료 된 후 찾은 위치를 참조하는 데 사용합니다. 그러나 i그 자체로는 그다지 의미가 없습니다. posn더 명확 할 수 있습니다. last_comment_posn매우 장황하지만 훨씬 명확합니다.

즉, 사용 : PEP-8은 변수 이름에 별도의 단어에 밑줄을 사용할 것을 권장 char_count하지 charcount

문자열 검색

파이썬 문자열에는 더 큰 문자열에서 부분 문자열을 검색하는 내장 함수가 있습니다. 예를 들어, 페이지 텍스트에서의 str.find첫 번째 항목을 빠르게 찾을 수 있습니다 <!--.

i = pagetext.find("<!--")

그러나 당신은 첫 번째 것을 찾는 것이 아닙니다. 당신은 마지막 하나를 찾고 있습니다. 파이썬은 역방향 찾기 기능으로 다시 다루었습니다 : str.rfind.

i = pagetext.rfind("<!--")

그러나 이것은 여전히 ​​마지막 발생의 색인을 찾습니다. 주석 표시 자 뒤의 문자를 원하므로 4 개의 추가 문자를 앞으로 건너 뛰어야합니다.

if i >= 0:
    newstring = pagetext[i+4:]

개선 된 코드

import requests
from collections import Counter

page = requests.get('http://www.pythonchallenge.com/pc/def/ocr.html')
page.raise_for_status()  # Crash if the request didn't succeed
page_text = page.text

posn = page_text.rfind("<!--")
print(posn)

if posn >= 0:
    comment_text = page_text[posn+4:]    # Fix!  This is to end of string, not end of comment!
    char_count = Counter(comment_text)
    print(char_count)