【问题标题】:compare a dictionary with excel file将字典与 Excel 文件进行比较
【发布时间】: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


    【解决方案1】:

    希望这是您正在寻找的,

    import xlrd
    import pandas as pd
    num_dic = {'one':'1','two':'2','neg_three':'-3'}
    
    loc = ("data.xlsx")
    wb = xlrd.open_workbook(loc)
    sheet = wb.sheet_by_index(0)
    sheet.cell_value(0, 0)
    list1 = []
    total = []
    for i in range(1, sheet.nrows): # start at 1 skips header row
        result = sheet.cell_value(i, 0).split(" ")
        num1 = 0
        for j in result:
            if j:
                num1 += int(num_dic[j])
        total.append(num1)
    
    sheet1 = pd.read_excel('data.xlsx')
    sheet1['total']=total
    writer = pd.ExcelWriter('data.xlsx')
    sheet1.to_excel(writer,'Sheet1',index=False,startcol=0)
    writer.save()
    

    【讨论】:

      【解决方案2】:

      我没有安装xlrd,所以以下只是理论上的,我没有测试。

      让我们逐块查看您的代码:

      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))
      

      这应该大致完成您想要的操作,并将读取的输入数据附加到list1。除非它不会读取您的数据的最后一行:您可能需要考虑将您的 range() 更改为 range(1, sheet.nrows + 1)

      接下来你把.join()全部放在一起,然后在上面做一个.split():

      # save the data to a list and then converted to a string for spliting 
      str1 = ''.join(list1)
      list2 = str1.spilt()
      

      我根本不会这样做,让list1 保持原样。您可以在计算时拆分值。

      然后您使用两个for 循环进行某种计算,并将它们全部存储到一个名为total 的变量中:

      # sum the values
      total = 0
      for i in list2:
       for key, value in num_dic.items():
         if key in i:
              total =+ int(value)
      

      这并没有真正做你想做的事,你想为每一行输入数据存储一个总数,然后可以将其写入你的结果文件。像这样的:

      # use actual integers in your lookup table
      num_dic = {'one':1,'two':2,'neg_three':-3} 
      
      list2 = []  ## this is your list containing the totals for each row
      for in_row in list1:
          row, string_value1, string_value2 = in_row.split()
          if string_value1 and string_value2:
              # values are not empty continue with calculation
              # use dict.get() to ensure a default value of 0 if not found
              total = num_dic.get(string_value1, 0) + num_dic.get(string_value2, 0)
              # append the total to the list
              list2.append(str(total))
          else:
              # one or both of the values is empty
              # appending an empty string to the result list2
              list2.append('')
      # at this point list2 contains all your results for each row of input
      

      您的最后一个块是将结果写入您的文件:

      # 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()
      

      正如我所说,我没有 xlrd,所以我无法评论写入文件,因此您现在需要将列表 list2 写入 XL 文件中的“总计”列。你如何做到这一点可能需要一些实验。

      【讨论】:

        猜你喜欢
        • 2014-10-10
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 1970-01-01
        • 2022-06-12
        • 1970-01-01
        • 2018-10-05
        • 1970-01-01
        相关资源
        最近更新 更多