[英]Read list of lists from text file and join and decode
我在包含未編碼的unicode的文本文件中有一個列表列表。 Python無需將我直接從文本文件中執行類似json.loads()
語句之類的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']]
輸出應該是三行字符串,其中上面的內容已編碼。 誰能告訴我我在做什么錯?
謝謝
也許像下一個代碼片段一樣?
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']
==>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.