2012-04-30 4 views
3

문자 버퍼 오브젝트, 개인 오해 예상 :파이썬 형식 오류 : 나는 오랜 시간 동안이 오류에 부착 된

TypeError: expected a character buffer object 

난 그냥 내가 오해 한 이해를, 그것은 유니 코드 문자열 사이의 차이점에 대해 뭔가 및 '간단한'문자열, 나는 유니 코드 하나 전달해야하는 동안 "정상적인"문자열 위의 코드를 사용하려고했습니다. 문자열이 실행을 깨기 전에 간단한 "u"를 잊었습니다./!!!

현재 유형 오류는 매우 불분명하며 여전히 있습니다.

제발, 내가 무엇을 놓치고 왜 "단순한"문자열이 "문자 버퍼 객체"가 아닌지 설명 할 수 있습니까?

하면 (here 추출 및 (c)) 아래의 코드 재현

def maketransU(s1, s2, todel=u""): 
    """Build translation table for use with unicode.translate(). 

    :param s1: string of characters to replace. 
    :type s1: unicode 
    :param s2: string of replacement characters (same order as in s1). 
    :type s2: unicode 
    :param todel: string of characters to remove. 
    :type todel: unicode 
    :return: translation table with character code -> character code. 
    :rtype: dict 
    """ 
    # We go unicode internally - ensure callers are ok with that. 
    assert (isinstance(s1,unicode)) 
    assert (isinstance(s2,unicode)) 
    trans_tab = dict(zip(map(ord, s1), map(ord, s2))) 
    trans_tab.update((ord(c),None) for c in todel) 
    return trans_tab 

#BlankToSpace_table = string.maketrans (u"\r\n\t\v\f",u"  ") 
BlankToSpace_table = maketransU (u"\r\n\t\v\f",u"  ") 
def BlankToSpace(text) : 
    """Replace blanks characters by realspaces. 

    May be good to prepare for regular expressions & Co based on whitespaces. 

    :param text: the text to clean from blanks. 
    :type text: string 
    :return: List of parts in their apparition order. 
    :rtype: [ string ] 
    """ 
    print text, type(text), len(text) 
    try: 
     out = text.translate(BlankToSpace_table) 
    except TypeError, e: 
     raise 
    return out 

# for SO : the code below is just to reproduce what i did not understand 
dummy = "Hello,\n, this is a \t dummy test!" 
for s in (unicode(dummy), dummy): 
    print repr(s) 
    print repr(BlankToSpace(s)) 

생산 :

u'Hello,\n, this is a \t dummy test!' 
Hello, 
, this is a  dummy test! <type 'unicode'> 32 
u'Hello, , this is a dummy test!' 
'Hello,\n, this is a \t dummy test!' 
Hello, 
, this is a  dummy test! <type 'str'> 32 

Traceback (most recent call last): 
    File "C:/treetaggerwrapper.error.py", line 44, in <module> 
    print repr(BlankToSpace(s)) 
    File "C:/treetaggerwrapper.error.py", line 36, in BlankToSpace 
    out = text.translate(BlankToSpace_table) 
TypeError: expected a character buffer object 

답변

11

문제는 bytestring의 translate 방법이 상이하다는 것이다 유니 코드 문자열의 translate 메소드. 반면,

S.translate(table) -> unicode

Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.

당신은 비 유니 코드 버전은 "길이 256의 문자열을"기대하고 있음을 볼 수 있습니다 여기에 유니 코드 버전 것

S.translate(table [,deletechars]) -> string

Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.

을 그리고 다음은 유니 코드를 지원하지 않는 버전의 문서화 문자열입니다 비 유니 코드 버전은 "매핑"(예 : dict)을 기대합니다. 문제는 여러분의 유니 코드 문자열이 버퍼 객체이고 비 유니 코드 (unicode)가 아닌 것은 물론 두 버퍼 모두입니다. 그러나 하나의 translate 메소드는 그러한 버퍼 객체를 기대하고 있고 다른 것은 아닙니다.

+0

감사합니다. 나는 이것을 아주 아주 멀리 이해하고 있었다! 나는 그것이 같은 대상이 아니라는 것을 알지 못했기 때문에 : / – user1340802

관련 문제