从文本文件中读取列表列表并加入和解码

时间:2016-09-26 17:19:07

标签: python unicode

我在包含非编码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']]

输出应该是三行字符串,上面的内容编码。谁能告诉我我做错了什么?

由于

1 个答案:

答案 0 :(得分: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']

==>
相关问题