Programing

파이썬 인터프리터가 문자열 작업에서 ASCII가 아닌 문자를 올바르게 처리하도록 만드는 방법은 무엇입니까?

lottogame 2020. 8. 18. 08:07
반응형

파이썬 인터프리터가 문자열 작업에서 ASCII가 아닌 문자를 올바르게 처리하도록 만드는 방법은 무엇입니까?


다음과 같은 문자열이 있습니다.

6 918 417 712

이 문자열을 자르는 명확한 방법은 (파이썬을 이해했듯이) 단순히 문자열이라는 변수에 있다고 말하는 것입니다 s.

s.replace('Â ', '')

그게 트릭을해야합니다. 그러나 물론 '\xc2'blabla.py 파일 의 비 ASCII 문자 가 인코딩되지 않았다고 불평합니다 .

다른 인코딩으로 전환하는 방법을 이해할 수 없었습니다.

여기에 코드가 있습니다. 실제로는 위와 동일하지만 지금은 컨텍스트에 있습니다. 파일은 메모장에 UTF-8로 저장되며 다음 헤더가 있습니다.

#!/usr/bin/python2.4
# -*- coding: utf-8 -*-

코드:

f = urllib.urlopen(url)

soup = BeautifulSoup(f)

s = soup.find('div', {'id':'main_count'})

#making a print 's' here goes well. it shows 6Â 918Â 417Â 712

s.replace('Â ','')

save_main_count(s)

더 이상 얻지 못합니다 s.replace...


Python 2는 ascii소스 파일의 기본 인코딩으로 사용합니다. 즉, 리터럴에서 ASCII가 아닌 유니 코드 문자를 사용하려면 파일 맨 위에 다른 인코딩을 지정해야합니다. Python 3은 utf-8소스 파일의 기본 인코딩으로 사용 하므로 문제가되지 않습니다.

참조 : http://docs.python.org/tutorial/interpreter.html#source-code-encoding

utf-8 소스 인코딩을 활성화하려면 다음 두 줄 중 하나에 입력합니다.

# -*- coding: utf-8 -*-

위의 내용은 문서에 있지만 이것도 작동합니다.

# coding: utf-8

추가 고려 사항 :

  • 소스 파일은 텍스트 편집기에서도 올바른 인코딩을 사용하여 저장해야합니다.

  • Python 2에서 유니 코드 리터럴은 u앞에 가 있어야합니다 . s.replace(u"Â ", u"")그러나 Python 3에서 와 같이 따옴표 만 사용하십시오. Python 2에서는 Python from __future__ import unicode_literals3 동작을 얻을 있지만 이것이 현재 모듈 전체에 영향을 미친다는 점에 유의하십시오.

  • s.replace(u"Â ", u"")s유니 코드 문자열이 아닌 경우에도 실패 합니다.

  • string.replace 새 문자열을 반환하고 제자리에서 편집하지 않으므로 반환 값도 사용하고 있는지 확인하십시오.


def removeNonAscii(s): return "".join(filter(lambda x: ord(x)<128, s))

편집 : 내 첫 번째 충동은 항상 필터를 사용하는 것이지만 생성기 표현식이 더 메모리 효율적이고 짧습니다 ...

def removeNonAscii(s): return "".join(i for i in s if ord(i)<128)

이것은 UTF-8 인코딩과 함께 작동한다는 것을 명심하십시오 (멀티 바이트 문자의 모든 바이트는 가장 높은 비트가 1로 설정되기 때문입니다).


>>> unicode_string = u"hello aåbäcö"
>>> unicode_string.encode("ascii", "ignore")
'hello abc'

다음 코드는 ASCII가 아닌 모든 문자를 물음표로 바꿉니다.

"".join([x if ord(x) < 128 else '?' for x in s])

Regex 사용 :

import re

strip_unicode = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)")
print strip_unicode.sub('', u'6Â 918Â 417Â 712')

Way too late for an answer, but the original string was in UTF-8 and '\xc2\xa0' is UTF-8 for NO-BREAK SPACE. Simply decode the original string as s.decode('utf-8') (\xa0 displays as a space when decoded incorrectly as Windows-1252 or latin-1:

Example (Python 3)

s = b'6\xc2\xa0918\xc2\xa0417\xc2\xa0712'
print(s.decode('latin-1')) # incorrectly decoded
u = s.decode('utf8') # correctly decoded
print(u)
print(u.replace('\N{NO-BREAK SPACE}','_'))
print(u.replace('\xa0','-')) # \xa0 is Unicode for NO-BREAK SPACE

Output

6 918 417 712
6 918 417 712
6_918_417_712
6-918-417-712

#!/usr/bin/env python
# -*- coding: utf-8 -*-

s = u"6Â 918Â 417Â 712"
s = s.replace(u"Â", "") 
print s

This will print out 6 918 417 712


I know it's an old thread, but I felt compelled to mention the translate method, which is always a good way to replace all character codes above 128 (or other if necessary).

Usage : str.translate(table[, deletechars])

>>> trans_table = ''.join( [chr(i) for i in range(128)] + [' '] * 128 )

>>> 'Résultat'.translate(trans_table)
'R sultat'
>>> '6Â 918Â 417Â 712'.translate(trans_table)
'6  918  417  712'

Starting with Python 2.6, you can also set the table to None, and use deletechars to delete the characters you don't want as in the examples shown in the standard docs at http://docs.python.org/library/stdtypes.html.

With unicode strings, the translation table is not a 256-character string but a dict with the ord() of relevant characters as keys. But anyway getting a proper ascii string from a unicode string is simple enough, using the method mentioned by truppo above, namely : unicode_string.encode("ascii", "ignore")

As a summary, if for some reason you absolutely need to get an ascii string (for instance, when you raise a standard exception with raise Exception, ascii_message ), you can use the following function:

trans_table = ''.join( [chr(i) for i in range(128)] + ['?'] * 128 )
def ascii(s):
    if isinstance(s, unicode):
        return s.encode('ascii', 'replace')
    else:
        return s.translate(trans_table)

The good thing with translate is that you can actually convert accented characters to relevant non-accented ascii characters instead of simply deleting them or replacing them by '?'. This is often useful, for instance for indexing purposes.


s.replace(u'Â ', '')              # u before string is important

and make your .py file unicode.


This is a dirty hack, but may work.

s2 = ""
for i in s:
    if ord(i) < 128:
        s2 += i

For what it was worth, my character set was utf-8 and I had included the classic "# -*- coding: utf-8 -*-" line.

However, I discovered that I didn't have Universal Newlines when reading this data from a webpage.

My text had two words, separated by "\r\n". I was only splitting on the \n and replacing the "\n".

Once I looped through and saw the character set in question, I realized the mistake.

So, it could also be within the ASCII character set, but a character that you didn't expect.

참고URL : https://stackoverflow.com/questions/1342000/how-to-make-the-python-interpreter-correctly-handle-non-ascii-characters-in-stri

반응형