如何将 excel 列读入列表?

How to read an excel column into a list?

我正在阅读 Excel 的专栏,如下所示:

import xlrd
import openpyxl
book = xlrd.open_workbook("English corpus.xlsx")
sheet = book.sheet_by_index(0)

data=[]
for row_index in xrange(1, sheet.nrows): # skip heading row
    timestamp, text, header, transporter, device_type = sheet.row_values(row_index,
                                                                         end_colx=5)
    print (text)
    data.append(text)

然后将 text 列中的单元格附加到 data 列表中(text 列是一个巨大的列,大约有 10000 个条目)。但是通过这种方式,数据是以 Unicode 类型格式附加的。而且我无法将其转换为字符串(出现 UnicodeEncode 错误 - 尝试了所有方法)。

任何人都可以告诉我任何其他方法来将单元格从 Excel 列读取到 python 列表中,以便列表元素仅为时间字符串而不是 Unicode?

编辑

如果您喜欢 openpyxl / xlrd,您可以尝试将数据编码为 unicode。 例如

s = u'about'
>>> s
u'about'
>>> s.encode("utf8")
'about'
>>> 

对于数据列表,您可以使用列表理解作为

data = [s.encode("utf8") for s in data]

为了更容易将 excel 列导入列表您可以尝试 pandasxls 数据加载到 pandas dataframe 然后发送dataframelist.

这会更有效率,因为 pandas 能够处理大量数据并且相对容易操作。

字符串之间的转换/Unicode等也在pandas级别处理。

这是一个例子。

file_name = 'words.xlsx'
import pandas as pd
xl_workbook = pd.ExcelFile(file_name)  # Load the excel workbook
df = xl_workbook.parse("Sheet1")  # Parse the sheet into a dataframe
aList = df['names'].tolist()  # Cast the desired column into a python list

因此 print aList 将显示为 unicode 数据。

   >>> print aList
    [u'ability (noun)', u'able (adjective)', u'about (preposition)', u'about (adverb)', u'above (adverb)', u'above (preposition)']

您可以使用列表理解将数据转换为 string

>>> [str(i) for i in aList]
['ability (noun)', 'able (adjective)', 'about (preposition)', 'about (adverb)', 'above (adverb)', 'above (preposition)']