programing

Python 3.1에서 문자열의 HTML 엔티티를 이스케이프 해제하려면 어떻게 해야 합니까?

madecode 2023. 5. 11. 23:20
반응형

Python 3.1에서 문자열의 HTML 엔티티를 이스케이프 해제하려면 어떻게 해야 합니까?

저는 사방을 둘러보았지만 파이썬 2.6 및 이전 버전에 대한 솔루션만 찾았고, 파이썬 3.X에서 이를 수행하는 방법에 대해서는 아무것도 없었습니다. (저는 Win7 박스에만 액세스할 수 있습니다.)

3.1에서 이 작업을 수행할 수 있어야 하며 가급적이면 외부 라이브러리 없이 수행할 수 있어야 합니다.현재 저는 httplib2가 설치되어 있고 명령 프롬프트 컬에 액세스할 수 있습니다(이렇게 페이지의 소스 코드를 얻습니다).안타깝게도 curl은 html 엔티티를 디코딩하지 않습니다. 제가 알기로는 문서에서 디코딩할 명령을 찾을 수 없었습니다.

예, Beautiful Soup이 작동하도록 여러 번 노력했지만 3.X에서는 성공하지 못했습니다.MS Windows 환경에서 python 3에서 작동하는 방법에 대해 명시적인 지침을 제공해 주시면 감사하겠습니다.

그래서 분명히 하자면, 저는 다음과 같이 문자열을 돌려야 합니다.Suzy & John"수지 & 존"과 같은 현으로 말입니다.

html.unescape 함수를 사용할 수 있습니다.

Python 3.4+에서 (J.F 덕분에).업데이트를 위한 Sebastian):

import html
html.unescape('Suzy & John')
# 'Suzy & John'

html.unescape('"')
# '"'

Python 3.3 이상 버전의 경우:

import html.parser    
html.parser.HTMLParser().unescape('Suzy & John')

Python2의 경우:

import HTMLParser
HTMLParser.HTMLParser().unescape('Suzy & John')

이 용도로 사용할 수 있습니다.이 모듈은 Python 표준 라이브러리에 포함되어 있으며 Python 2.x와 Python 3.x 간에 이동할 수 있습니다.

>>> import xml.sax.saxutils as saxutils
>>> saxutils.unescape("Suzy & John")
'Suzy & John'

분명히 저는 이것을 게시하는 것 외에는 아무것도 할 수 없을 정도로 높은 평판을 가지고 있지 않습니다.우넛부의 대답은 인용구를 벗어나지 않습니다.제가 발견한 유일한 기능은 다음과 같습니다.

import re
from htmlentitydefs import name2codepoint as n2cp

def decodeHtmlentities(string):
    def substitute_entity(match):        
        ent = match.group(2)
        if match.group(1) == "#":
            return unichr(int(ent))
        else:
            cp = n2cp.get(ent)
            if cp:
                return unichr(cp)
            else:
                return match.group()
    entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")
    return entity_re.subn(substitute_entity, string)[0]

페이지에서 얻은 것입니다.

Python 3.x에도 html.entity가 있습니다.

저의 경우, 3 이스케이프 함수로 이스케이프된 html 문자열을 가지고 있습니다.한 시간 동안 검색해도 아무 소용이 없어서 저는 제 필요를 충족시키기 위해 이 재수강 기능을 썼습니다.여기 있어요.

def unescape(string):
    index = string.find("%")
    if index == -1:
        return string
    else:
        #if it is escaped unicode character do different decoding
        if string[index+1:index+2] == 'u':
            replace_with = ("\\"+string[index+1:index+6]).decode('unicode_escape')
            string = string.replace(string[index:index+6],replace_with)
        else:
            replace_with = string[index+1:index+3].decode('hex')
            string = string.replace(string[index:index+3],replace_with)
        return unescape(string)

편집-1 유니코드 문자를 처리하는 기능이 추가되었습니다.

이것이 내장 라이브러리인지 아닌지는 잘 모르겠지만 당신이 필요로 하는 것처럼 보이고 3.1을 지원합니다.

보낸 사람: http://docs.python.org/3.1/library/xml.sax.utils.html?highlight=html%20unescape

xml.sax.saxutils.unescape(데이터, 엔티티={}) 데이터 문자열에서 '&', '<,' 및 '>'를 unescape합니다.

언급URL : https://stackoverflow.com/questions/2360598/how-do-i-unescape-html-entities-in-a-string-in-python-3-1

반응형