2017-03-08 1 views
0

mylocal 컴퓨터의 elasticsearch 색인에 텍스트 파일을 가져올 수있었습니다. 내가 python3를 사용하고 난 개인적으로 python2 덜 문제가되었다python3에서 혼합 된 인코딩 된 텍스트에서 비 ASCII 문자를 건너 뛰는 것이 가장 좋습니다.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 79: ordinal not in range(128) 

, 어쩌면 그냥 좌절입니다 : 내가 좋아하는 데 오류를 유지하기 때문에

생산 시스템에 가상 환경을 사용에도 불구하고 악몽이다 시간 낭비.

나는 비 아스키 문자 제거 또는 처리 할 수없는 나는 왜, 내가 이해할 수 :

내가 가져올 시도를 :

from unidecode import unidecode 
def remove_non_ascii(text): 
    return unidecode(unicode(text, encoding = "utf-8")) 

, 어떤 성공을 python2를 사용하지 않습니다. python3에

다시 :

import string 
printable = set(string.printable) 

''.join(filter(lambda x: x in printable, 'mixed non ascii string') 

성공하지

import codecs 
with codecs.open(path, encoding='utf8') as f: 
.... 

시도 성공하지 :

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

성공하지

,

https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize

성공하지 ...

의 모든

위 가진 다음과 같은 오류에,이, 나는 매우 성가신 유지되는 스트립 또는 비 ASCII를 처리 할 수없는 것 같다

with open(path) as f: 
    for line in f: 
     line = line.replace('\n','') 
     el = line.split('\t') 
     print (el) 
     _id = el[0] 
     _source = el[1] 
     _name = el[2] 
     # _description = ''.join(filter(lambda x: x in printable, el[-1])) 
     # 
     _description = remove_non_ascii(el[-1]) 
     print (_id, _source, _name, _description, setTipe(_source)) 
     action = { 
      "_index": _indexName, 
      "_type": setTipe(_source), 
      "_id": _source, 
      "_source": { 
       "name": _name, 
       "description" : _description 
       } 
      } 
     helpers.bulk(es, [action]) 

    File "<stdin>", line 22, in <module> 
    File "/usr/local/lib/python2.7/dist-packages/elasticsearch/helpers/__init__.py", line 194, in bulk 
    for ok, item in streaming_bulk(client, actions, **kwargs): 
    File "/usr/local/lib/python2.7/dist-packages/elasticsearch/helpers/__init__.py", line 162, in streaming_bulk 
    for result in _process_bulk_chunk(client, bulk_actions, raise_on_exception, raise_on_error, **kwargs): 
    File "/usr/local/lib/python2.7/dist-packages/elasticsearch/helpers/__init__.py", line 87, in _process_bulk_chunk 
    resp = client.bulk('\n'.join(bulk_actions) + '\n', **kwargs) 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 79: ordinal not in range(128) 

python3에서 인코딩 문제를 처리하는 "확실한"방법을 원합니다. 다른 컴퓨터에서 같은 스크립트를 사용하고 다른 결과를 얻고 싶습니다.

+0

실제로 해결하려는 문제를 재현하는 실제 예제를 제공하면 문제를 훨씬 쉽게 해결할 수 있습니다. [묻는 방법] (https://stackoverflow.com/help/how-to-ask) 및 [최소, 완전하고 검증 가능한 예 만들기] (https://stackoverflow.com/help/mcve)를 참조하십시오. –

답변

1

ASCII 문자는 0-255입니다. .

def remove_non_ascii(text): 
    ascii_characters = "" 
    for character in text: 
     if ord(character) <= 255: 
      ascii_characters += character 
    return ascii_characters