【发布时间】:2020-10-24 01:12:00
【问题描述】:
我在 Excel 中替换了很多值,所以我有一个包含数百个键的字典,但是当一个键有斜杠 (/) 时,它不会输入 if。
如您所见,我尝试使用 doble、//,并在之前添加 r 以使其成为文字。
当我在 dict.keys() 中执行 is ("stringwith /slash") 时,我得到一个 True,但是当我运行程序时,它们被跳过,就好像它们不存在一样。
import xlwt
import xlrd
dictForReplacement={}
for i in range(0,101):
x = "Estigfend" + str(i) + str(i)+ " puntos de 100"
dictForReplacement[x] = str(i)
x = "Estigfend" + str(i) + str(i)+ " puntos de 100Completada con retraso"
dictForReplacement[x] = str(i)
x = "Estigfend" + str(i) + str(i)+ " puntos de 100Presentada de nuevo"
dictForReplacement[x] = str(i)
x = "Estigfend" + str(i) + str(i)+ " puntos de 100Borrador"
dictForReplacement[x] = str(i)
x = "Estigfend" + str(i) + str(i)+ " puntos de 100Sin entregar"
dictForReplacement[x] = str(i)
x = "Estigfend" + str(i)+"/100" + str(i)+ " puntos de 100Sin entregar"
dictForReplacement[x] = str(i)
x = "Estigfend" + str(i)+"/100" + str(i)+ " puntos de 100"
dictForReplacement[x] = str(i)
dictForReplacement[r"EstigfendSin entregar"] = "NP"
dictForReplacement["EstigfendTarea asignada"] = "TA"
#here is the problem, the number was in case I founded the solution
dictForReplacement[r"Estigfend /100Sin calificación"] = "NP 00"
dictForReplacement[r"Estigfend /100Sin calificación"] = "NC 0"
dictForReplacement["Estigfend //100Sin calificación"] = "NC 1"
dictForReplacement[r'Estigfend //100Sin calificaciónCompletada con retraso'] = "NC 2"
dictForReplacement['Estigfend /100Sin calificaciónCompletada con retraso'] = "NC 3"
dictForReplacement[r"Estigfend /100Sin calificaciónCompletada con retraso"] = "NC 4"
dictForReplacement[r"Estigfend /100Sin calificaciónBorrador"] = "NC 5"
dictForReplacement["Estigfend /100Sin calificación"] = "NP"
###################################################
#heres the if
ExcelNewName = "AAA"
########################################## Name of Excel to be modified
workbook = xlrd.open_workbook('Intento Calificaciones clear.xlsx')
sheet = workbook.sheet_by_name('Hoja1')
#write the data into new Excel file:
new_workbook = xlwt.Workbook()
new_sheet = new_workbook.add_sheet('Hoja1')
for i in range(sheet.nrows):
data = [sheet.cell_value(i, col) for col in range(sheet.ncols)]
for index, value in enumerate(data):
if value in dictForReplacement.keys():
new_sheet.write(i, index, str(dictForReplacement.get(value)))
else:
new_sheet.write(i, index, value)
new_workbook.save(ExcelNewName+'.xls')
这是我没有 Ktinder 的代码,因为它是一个 GUI,我知道这里不需要它
所以现在你也可以运行它了。
edit4:接下来的 3 行错误 Idk如何在这里添加一个excel文件,最大的问题是带有/的字符串,所以只需创建一个页面并有一个单元格: Estigfend /100Sin calificación
edit2:有人说肯定是excel在添加其他东西,我会调查一下
【问题讨论】:
-
为了简化您的字符串创建,请考虑使用 f 字符串。例如,您的第一条语句将变为:
x = f"Estigfend{i}{i} puntos de 100"这可能会使识别变量名称中的错误更容易识别 -
为了更容易调试问题,尝试在循环的每个实例中打印
value。也许您的 excel 文档包含您没有考虑到的字符,例如'\n',或者导致if语句失败的其他空格。就其本身而言,带有/的密钥与没有的密钥没有明显的不同,所以我怀疑这里还有其他事情发生。 -
@zvone,我认为现在是可复制的,我加入了代码,除此之外唯一的事情就是拥有一个 excel 并输入该名称或更改 var
-
感谢@CollinHeist 的建议,双方都会调查一下
标签: python dictionary spyder xlrd xlwt