Skip to content

Instantly share code, notes, and snippets.

@nicoster
Last active December 31, 2015 16:49
Show Gist options
  • Select an option

  • Save nicoster/8016364 to your computer and use it in GitHub Desktop.

Select an option

Save nicoster/8016364 to your computer and use it in GitHub Desktop.
sort components for building a train. nicoster@gmail. 2013. all rights reserved
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys
reload(sys)
sys.setdefaultencoding('gbk')
_debug = False
_index_node = 1
_index_parent = 3
def sort(records, parent, outputs, depth = 1):
children = []
for record in records:
if record[1] == parent:
children.append(record)
record[1] = 'deleted'
for child in children:
if _debug: print ' ' * depth, child[0], parent
outputs.append(child[2])
sort(records, child[0], outputs, depth + 1)
def usage(argv = None):
print 'sort components for building a train. \nnicoster@gmail. 2013. all rights reserved.\n'
if not argv: return
print 'Usage:', argv[0], 'file-name [root-node] [debug]'
print '\tif root-node isn\'t specified, this tool tries to get the root-node from the file. \n\t(root-node does not have a parent node)'
def main(argv):
if len(argv) < 2:
usage(argv)
return
else:
usage()
file_name = argv[1]
print 'file-name:', file_name
root = ''
global _debug
if len(argv) >= 3:
root = argv[2]
if root == 'debug':
root = ''
_debug = True
print 'root-node:', root
if not root:
print ' (since you didn\'t specify a root-node, please make sure there\'s one in the file)'
if len(argv) == 4 and argv[3] == 'debug':
_debug = True
print 'debug:', _debug
try:
fp = open(file_name, 'r')
content = fp.read()
fp.close()
except Exception, e:
print 'read', file_name, e
return
records = []
rows = content.split('\n')
global _index_parent
global _index_node
headers = rows[0].split(',', 5)
_index_node = headers.index(u'零件号')
_index_parent = headers.index(u'所属零件号')
if not _index_node or not _index_parent:
print 'cannot locate headers. abort.'
return
print 'node-index:', _index_node
print 'parent-index:', _index_parent
for i, row in enumerate(rows[1:]): # exclude the header
# print i, row
if not row: continue
fields = row.split(',', 5)
node = fields[_index_node]
parent = fields[_index_parent]
records.append([node, parent, row])
# print node, parent
# return
print 'read records:', len(records)
outputs = [rows[0]]
sort(records, root, outputs)
file_name = 'sorted-' + file_name
try:
fp = open(file_name, 'w')
fp.write('\n'.join(outputs))
fp.close()
print 'write', len(outputs) - 1, 'records into', file_name
except Exception, e:
print 'write', file_name, e
return
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment