2016-10-29 13 views
-2

標題中的問題可能並不能反映我真正想要的東西......我會在這裏盡我所能。如何從Python中的十六進制(字節字符串)中讀取單個字符?

我有一個十六進制字符串的下面表示作爲字節串:

S = '\ X00 \ X00 \ X01B \ x90bM \ xe0 \ X00 \ X00 \ X00?'

我有一個hbase表,其中行鍵的格式爲's'。但是,當我經過的範圍內這種格式會產生一個錯誤:「UTF-8不能解碼字節......」

sparkconf = {「hbase.zookeeper.quorum」:「myHostIP」,「hbase.mapreduce .inputtable「:」myHbaseTable「,」hbase.mapreduce.scan.columns「:」c1:c2「,」hbase.mapreduce.scan.row.start「:startRow,」hbase.mapreduce.scan.row.stop「: endRow}

似乎startRow和endRow必須是字符串?

如果是這樣,有沒有辦法將s ='\ x00 \ x00 \ x01b?\ x90bM \ xe0 \ x00 \ x00 \ x00'轉換爲一個SAME字符串?

這樣,我的意思並不是轉換十六進制牛逼字符串,我的意思是,我需要一個字符串,如str_s = MAKESTRING(S)會導致str_s ='\ X00 \ X00 \ X01B?\ x90bM \ xe0 \ X00 \ X00 \ X00'其中str_s [0] = '\',str_s [1] = 'X',str_s [2] = '0' 等...

非常感謝的幫助,我是python,pyspark和hbase的新手。

+0

你的字符串從哪裏來?你以某種方式生成它? – maij

+0

是的,前4個字節是一個int,最後8個是一個double。所以,確切的問題是:它不清楚如何hbase_rdd = sc.newAPIHadoopRDD(「org.apache.hadoop.hbase.mapreduce.TableInputFormat」,「org.apache.hadoop.hbase.io.ImmutableBytesWritable」,「org.apache .hadoop.hbase.client.Result「,keyConverter = keyConv,valueConverter = valueConv,conf = sparkconf) 正在解釋開始和結束行。我已經解決了utf-8問題如下: s = u'\ x00 \ x00 \ x01b?\ x90bM \ xe0 \ x00 \ x00 \ x00' s = s.encode('utf-8') 但是我從範圍掃描獲得空集! 感謝您幫助 –

+0

當我在掃描中使用與hbase shell相同格式的相同範圍(開始和結束)時,它可以工作,而不是newAPIHadoopRDD! –

回答

0

你可能想使用類似以下內容:

def printable_repr(s): 
    """ Convert to a printable representation. 

    Replace each nonprintable ascii byte in s by its 
    hex representation (\xXX) 
    """ 
    printable_s = [] 
    for c in s: 
     if 32 <= ord(c) and ord(c) <= 126: 
      printable_s.append(c) 
     else: 
      printable_s.append("\\%02x" % ord(c)) 
    return ''.join(printable_s) 


s = '\x00\x00\x01b?\x90bM\xe0\x00\x00\x00' 
s_str = printable_repr(s) 

print("s_str: " + s_str) 

for i in range(0, len(s_str)): 
    print(str(i) + ": " + s_str[i]) 

腳本,輸出結果(Python的3.4.2):

s_str: \00\00\01b?\90bM\e0\00\00\00 
0: \ 
1: 0 
2: 0 
3: \ 
4: 0 
5: 0 
6: \ 
7: 0 
8: 1  
9: b 
10: ? 
11: \ 
12: 9 
13: 0 
14: b 
15: M 
16: \ 
17: e 
18: 0 
19: \ 
20: 0 
21: 0 
22: \ 
23: 0 
24: 0 
25: \ 
26: 0 
27: 0 

當然,你可以很容易,如果你簡化腳本還希望用它們的十六進制表示法替換可打印的ascii字符。

相關問題