def importTableText(self): """Import a file with a tab-delimited table with header row. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel(True) typeName = _('TABLE') tableFormat = nodeformat.NodeFormat(typeName, model.formats) model.formats.addTypeIfMissing(tableFormat) with open(self.filePath, 'r', encoding=globalref.localTextEncoding) as f: headings = [ self.correctFieldName(name) for name in f.readline().split('\t') ] tableFormat.addFieldList(headings, True, True) lineNum = 1 for line in f: lineNum += 1 if line.strip(): entries = line.split('\t') node = treenode.TreeNode(model.root, typeName, model) model.root.childList.append(node) try: for heading in headings: node.data[heading] = entries.pop(0) except IndexError: pass # fewer entries than headings is OK if entries: self.errorMessage = ( _('Too many entries on Line {0}').format(lineNum)) return None # abort if too few headings node.setUniqueId(True) return model
def importL5X(self): """Import RSLogix XML file. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel() tree = ElementTree.ElementTree() try: tree.parse(self.filePath) self.loadL5XNode(tree.getroot(), model, None) except ElementTree.ParseError: return None for elemFormat in model.formats.values(): # fix formats if required if not elemFormat.getLines()[0]: elemFormat.changeTitleLine(elemFormat.name) for fieldName in elemFormat.fieldNames(): elemFormat.addOutputLine('{0}="{{*{1}*}}"'.format( fieldName, fieldName)) if not elemFormat.fieldDict: elemFormat.addField(genericXmlTextFieldName) if model.root: for node in model.root.descendantGen(): node.updateUniqueId() return model return None
def importTabbedText(self): """Import a file with tabbed title structure. Return the model if import is successful, otherwise None """ textLevelList = [] with open(self.filePath, 'r', encoding=globalref.localTextEncoding) as f: for line in f: text = line.strip() if text: level = line.count('\t', 0, len(line) - len(line.lstrip())) textLevelList.append((text, level)) if textLevelList: if len([item for item in textLevelList if item[1] == 0]) > 1: textLevelList = [(text, level + 1) for text, level in textLevelList] textLevelList.insert(0, (treemodel.defaultRootName, 0)) model = treemodel.TreeModel(True) text, level = textLevelList.pop(0) if level == 0: model.root.setTitle(text) if model.root.loadChildLevels(textLevelList): return model return None
def importOdfText(self): """Import an ODF format text file outline. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel(True) odfFormat = model.formats[treeformats.defaultTypeName] odfFormat.addField(textFieldName) odfFormat.changeOutputLines([ '<b>{{*{0}*}}</b>'.format(nodeformat.defaultFieldName), '{{*{0}*}}'.format(textFieldName) ]) odfFormat.formatHtml = True try: with zipfile.ZipFile(self.filePath, 'r') as f: text = f.read('content.xml') except (zipfile.BadZipFile, KeyError): return None try: rootElement = ElementTree.fromstring(text) except ElementTree.ParseError: return None nameSpace = '{urn:oasis:names:tc:opendocument:xmlns:text:1.0}' headerTag = '{0}h'.format(nameSpace) paraTag = '{0}p'.format(nameSpace) numRegExp = re.compile(r'.*?(\d+)$') currentNode = model.root currentLevel = 0 for elem in rootElement.iter(): if elem.tag == headerTag: style = elem.get('{0}style-name'.format(nameSpace), '') try: level = int(numRegExp.match(style).group(1)) except AttributeError: return None if level < 1 or level > currentLevel + 1: return None while (currentLevel >= level): currentNode = currentNode.parent currentLevel -= 1 node = treenode.TreeNode(currentNode, odfFormat.name, model) currentNode.childList.append(node) node.data[nodeformat.defaultFieldName] = ''.join( elem.itertext()) node.setUniqueId(True) currentNode = node currentLevel = level elif elem.tag == paraTag: text = ''.join(elem.itertext()) origText = currentNode.data.get(textFieldName, '') if origText: text = '{0}<br />{1}'.format(origText, text) node.data[textFieldName] = text return model
def importXbel(self): """Import an XBEL format bookmark file. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel() model.formats = self.createBookmarkFormat() tree = ElementTree.ElementTree() try: tree.parse(self.filePath) except ElementTree.ParseError: return None self.loadXbelNode(tree.getroot(), model, None) if model.root: return model return None
def importMozilla(self): """Import an HTML mozilla-format bookmark file. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel() model.formats = self.createBookmarkFormat() with open(self.filePath, 'r', encoding='utf-8') as f: text = f.read() try: handler = HtmlBookmarkHandler(model) handler.feed(text) handler.close() except html.parser.HTMLParseError: return None return model
def importTextLines(self): """Import a text file, creating one node per line. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel(True) with open(self.filePath, 'r', encoding=globalref.localTextEncoding) as f: for line in f: line = line.strip() if line: node = treenode.TreeNode(model.root, model.root.formatName, model) model.root.childList.append(node) node.data[nodeformat.defaultFieldName] = line node.setUniqueId(True) return model
def importTextPara(self): """Import a text file, creating one node per paragraph. Blank line delimited. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel(True) with open(self.filePath, 'r', encoding=globalref.localTextEncoding) as f: text = f.read() paraList = text.split('\n\n') for para in paraList: para = para.strip() if para: node = treenode.TreeNode(model.root, model.root.formatName, model) model.root.childList.append(node) node.data[nodeformat.defaultFieldName] = para node.setUniqueId(True) return model
def importTreePad(self): """Import a Treepad file, text nodes only. Return the model if import is successful, otherwise None. """ model = treemodel.TreeModel(True) tpFormat = model.formats[treeformats.defaultTypeName] tpFormat.addFieldList([textFieldName], False, True) tpFormat.fieldDict[textFieldName].changeType('SpacedText') with open(self.filePath, 'r', encoding=globalref.localTextEncoding) as f: textList = f.read().split('<end node> 5P9i0s8y19Z') nodeList = [] for text in textList: text = text.strip() if text: try: text = text.split('<node>', 1)[1].lstrip() lines = text.split('\n') title = lines[0] level = int(lines[1]) lines = lines[2:] except (ValueError, IndexError): return None node = treenode.TreeNode(None, tpFormat.name, model) node.data[nodeformat.defaultFieldName] = title node.data[textFieldName] = '\n'.join(lines) node.level = level node.setUniqueId(True) nodeList.append(node) parentList = [] for node in nodeList: if node.level != 0: parentList = parentList[:node.level] node.parent = parentList[-1] parentList[-1].childList.append(node) parentList.append(node) model.root = nodeList[0] return model
def __init__(self): """Initialize a TreeOpenFile object. """ self.model = treemodel.TreeModel() self.rootAttr = {} self.duplicateIdList = []