如何摆脱Python Openpyxl中的“ 0”

时间:2019-11-28 20:23:46

标签: python excel python-3.x openpyxl

我有一段代码,它使用openpyxl在excel中读取了单元格的单元格值,我想将这些值放入数组中,以便可以使用所需的特定值。当我将我的值放入数组时,它的行为却很奇怪。

这是代码:

import datetime,openpyxl,re
from openpyxl.styles import Font
from openpyxl.styles.colors import RED
wb = openpyxl.load_workbook("customers.xlsx", data_only = 'True')
print(wb.sheetnames)
sh = wb["FEB 2019"]

#FROM HERE TO 

def room():

    counter = 0

    for row in sh["A20":"A31"]:
        for cell in row:
            result=[0]*12
            result[counter] = cell.value
            #results=[cell.value() for x in range (13)]
            result[counter]= re.sub("[A-Z]+","",result[counter])
            result[counter]=result[counter].strip()
            counter += 1 
            print(result)
#HERE
def names():
    results=[""]*113
    for row in sh["B20":"H31"]:
        print("")
        #room()
        for cell in row:
            b = cell.value
            result = re.sub("[0-9]+","", str(b))
            result = re.sub(r'[£]',"",result)
            result = re.sub(r'[,]',"",result)
            result = re.sub(r'[.]',"",result)
            result = re.sub("BEDROOM","",result)
            result = re.sub("STUDIO","",result)
            result = re.sub("APARTMENT","",result)
            result = re.sub("COSY RM","",result)
            result = re.sub("COSY","",result)
            result = re.sub("GARDEN","",result)
            if result == "None" :
                None
            else:
                for counter in range(1):
                    print (result)
                    results[counter]=result
    #print(results[0])

#names()
room()

我把整个代码仅供参考,但是我在代码中标记了我要讨论的地方

这是我的输出:

['FEB 2019', 'JAN 2019', 'MARCH 2019', 'APRIL 2019', 'MAY 2019', 'JUNE 2019', 'JULY 2019', 'AUGUST 2019', 'SEPTEMBER 2019', 'OCTOBER 2019', 'NOVEMBER 2019', 'DECEMBER 2019']
['1', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, '2', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, '3', 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, '4', 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, '5', 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, '11', 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, '12', 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, '6', 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, '7', 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, '8', 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '9', 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '10']

如果在您自己的计算机上尝试使用该模块,则可能会引发错误。 总结一下我的问题是,代码为我提供了这样的输出,因为我想要的是“ 1,2,3,4,5”,因此没有“ 0” 如果您发现我可以处理或解决的其他问题,我欢迎您提出建议,但主要问题如上所述。 如果需要,我可以共享该文件的示例。

编辑问题已解决,这是现在的样子:

def room():
    counter = 0
    result=[]*13
    for row in sh["A20":"A31"]:
        for cell in row:
            result.append(cell.value)
            result[counter] = re.sub("[A-Z]+","",(result[counter]))
            counter += 1 
    return (result)

0 个答案:

没有答案