【发布时间】:2018-07-09 09:09:18
【问题描述】:
我有一个包含单词和字典的文件,其中包含每个单词作为键,分数作为值:
data.xlsx
1. one neg_three
2. one two
字典:
num_dic = {'one':'1','two':'2','neg_three':'-3',....}
我想要的是比较每个键与 excel 文件中的每一行,并使用字典中的值对所有单词的值求和,并将结果保存在 excel 文件的最后一列中。这是我的代码
import xlrd
loc = ("data.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
list1 = []
for i in range(1, sheet.nrows): # start at 1 skips header row
list1.append(sheet.cell_value(i, 0))
# save the data to a list and then converted to a string for spliting
str1 = ''.join(list1)
list2 = str1.spilt()
# sum the values
total = 0
for i in list2:
for key, value in num_dic.items():
if key in i:
total =+ int(value)
# save the result in excel file
expData = pd.DataFrame(total, columns = ['total'])
writer = ExcelWriter('data.xlsx')
expData.to_excel(writer,'Sheet1',index=False,startcol=1)
writer.save()
输出应该是这样的:
data.xlsx:
data total
1. one neg_three -2
2. one two 3
谁能在我的代码中给我建议?因为它不起作用。提前致谢
【问题讨论】:
标签: python python-3.x list dictionary dataframe