2016-09-26 115 views
0

我有一個包含非編碼unicode的文本文件中的列表列表。 Python正在將列表中的對象識別爲一個列表,而我沒有像從文本文件中直接獲取json.loads()語句那樣執行任何操作。從文本文件中讀取列表並加入並解碼

當我嘗試讀取文本文件的所有行,然後執行for循環遍歷每個子列表時,什麼都不會發生。在嘗試加載到JSON之前,當我嘗試編碼整個對象時,沒有任何事情發生。

這是我的代碼:

import glob 

myglob = 'C:\\mypath\\*.txt' 
myglob = ''.join(myglob) 

for name in glob.glob(myglob): 

    split_name = name.split('\\')[5] 

    with open(name) as f: 

     content = f.readlines() 

     for xx in content: 

      print xx.encode('utf-8') 

輸入數據看起來像這樣:

[['Alexis S\xe1nchez', 'Alexis', 'S\xe1nchez', 'Forward', 'Arsenal', '13', '25244'],['H\xe9ctor Beller\xedn', 'H\xe9ctor', 'Beller\xedn', 'Defender', 'Arsenal', '13', '125211'],['Libor Koz\xe1k', 'Libor', 'Koz\xe1k', 'Forward', 'Aston Villa', '24', '67285']] 

輸出應該三行編碼上述內容串。誰能告訴我我做錯了什麼?

謝謝

回答

0

也許像下一個代碼片段?

listInput = [['Alexis S\xe1nchez', 'Alexis', 'S\xe1nchez', 'Forward', 'Arsenal', '13', '25244'], 
    ['H\xe9ctor Beller\xedn', 'H\xe9ctor', 'Beller\xedn', 'Defender', 'Arsenal', '13', '125211'], 
    ['Libor Koz\xe1k', 'Libor', 'Koz\xe1k', 'Forward', 'Aston Villa', '24', '67285']] 

for listItem in listInput: 

    for aItem in listItem: 
     aItem = aItem.encode('utf-8') 

    print (listItem) 

輸出

==> python D:\test\Python\39708736.py 
['Alexis Sánchez', 'Alexis', 'Sánchez', 'Forward', 'Arsenal', '13', '25244'] 
['Héctor Bellerín', 'Héctor', 'Bellerín', 'Defender', 'Arsenal', '13', '125211'] 
['Libor Kozák', 'Libor', 'Kozák', 'Forward', 'Aston Villa', '24', '67285'] 

==> 
相關問題