【发布时间】:2017-09-15 02:24:50
【问题描述】:
我正在使用此代码读取一个 excel 文件。
from xlrd import open_workbook
book = open_workbook('excel_demo.xlsx')
sheet = book.sheet_by_index(0)
# read header values into the list
keys = [sheet.cell(0, col_index).value for col_index in xrange(sheet.ncols)]
dict_list = []
for row_index in xrange(1, sheet.nrows):
d = {keys[col_index]: sheet.cell(row_index, col_index).value
for col_index in xrange(sheet.ncols)}
dict_list.append(d)
print dict_list
我得到的输出是字典列表的形式,如下所示:
[{'A': 1.0, 'C': 3.0, 'B': 2.0},
{'A': 5.0, 'C': 7.0, 'B': 6.0}]
就我而言,我需要将此列表作为训练集传递给我的朴素贝叶斯算法。所以我需要如下的东西:
train_data = [({"a": 4, "b": 1, "c": 0}, "1:0"),
({"a": 5, "b": 2, "c": 1}, "2:1"),
({"a": 0, "b": 3, "c": 4}, "3:4"),
({"a": 5, "b": 1, "c": 1}, "1:1"),
({"a": 1, "b": 4, "c": 3}, "4:3")]
如何在 python 代码中实现这种转换。在这种情况下,正则表达式会有所帮助。非常感谢。
【问题讨论】:
标签: python regex list dictionary naivebayes