import rhinoscriptsyntax as rs

def exportNameOcc(_objs_ids):
    namesColumn = []
    if _objs_ids:
        for obj in _objs_ids:
            name = rs.ObjectName(obj)
            if name:
                namesColumn.append(name)
        if len(namesColumn) > 0: 
            namesColumnU = set(namesColumn)
            namesColumnU = list(namesColumnU)

            countColumn = []
            for nU in namesColumnU:
                   number = namesColumn.count(nU)
                   countColumn.append(number)

            mergedL = []
            for i in range(len(namesColumnU)):
                mergedL.append((countColumn[i], namesColumnU[i]))
            mergedL.sort(reverse=True)
            
            filename = rs.SaveFileName("Save csv file","*.csv||", None, "ObjectNamesOccurrences", "csv")
            file = open(filename, 'w')
            headerline = "Names, Occurrences\n"
            file.write(headerline)
            for i in range(len(namesColumnU)):
                name = mergedL[i][1]
                occ = mergedL[i][0]
                line = "%s,%i \n" %(name, occ)
                file.write(line)
            file.close()
            print "Done"

        else:
            print "You do not have named objects. Function terminated"
            return

    else:
        print "Your 3dm file is empty or you did not select objects. Function terminated"
        return

rs.Command("_SelAll")
objs_ids = rs.GetObjects("", preselect=True)
exportNameOcc(objs_ids)