Best Python code snippet using slash
txt2tei.py
Source:txt2tei.py
1#!/usr/bin/env python32import argparse3INDENTATION_CHAR = " "4def print_indented(text, level=0):5 print("{}{}".format("".join([INDENTATION_CHAR] * level), text))6def print_header(data):7 print(8 '<?xml version="1.0" encoding="UTF-8"?>\n'9 '<?xml-model http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng application/xml http://relaxng.org/ns/structure/1.0\n'10 'http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng application/xml http://purl.oclc.org/dsdl/schematron?>\n'11 '<TEI xmlns="http://www.tei-c.org/ns/1.0">\n'12 )13 print_indented('<teiHeader>', 1)14 print_header_description(data, level=2)15 print_header_cast(data, level=2)16 print_indented('</teiHeader>', 1)17def print_header_description(data, level):18 print_indented('<fileDesc>', level) # fileDesc BEGIN19 # TITLE20 # TODO: title-type?21 # TODO: author-key?22 print_indented('<titleStmt>', level + 1)23 print_indented('<title>{}</title>'.format(data["title"]), level + 2) # Drama title24 print_indented('<author>{}</author>'.format(data["author"]), level + 2) # Drama author25 print_indented('</titleStmt>', level + 1)26 # EDITION27 # TODO: keep empty?28 print_indented('<editionStmt>', level + 1)29 print_indented('<edition n=""></edition>', level +2)30 print_indented('</editionStmt>', level + 1)31 # PUBLICATION32 # TODO: AUTHORITY metadata?33 # TODO: PUBLISHER metadata?34 # TODO: DATE, TIME metadata?35 # TODO: LICENCE metadata?36 print_indented('<publicationStmt>', level + 1)37 print_indented('<p>Information about the publication.</p>', level + 2)38 print_indented('</publicationStmt>', level + 1)39 # DESCRIPTION40 # TODO BIBL metadata?41 # TODO: URL metadata?42 print_indented('<sourceDesc>', level + 1)43 print_indented('<p>{}</p>'.format(data["description"]), level + 2) # Drama description44 print_indented('</sourceDesc>', level + 1)45 print_indented('</fileDesc>', level) # fileDesc END46 # ENCODING47 # TODO: keep empty?48 print_indented('<encodingDesc>', level)49 print_indented('<p/>', level + 1)50 print_indented('</encodingDesc>', level)51def print_header_cast(data, level):52 print_indented('<profileDesc>', level) # profileDesc BEGIN53 print_indented('<particDesc>', level + 1) # particDesc BEGIN54 print_indented('<listPerson>', level + 2)55 for character in data["cast"]:56 print_header_cast_single(character["xml_id"], character["name"], character["role"], level=(level + 3))57 print_indented('</listPerson>', level + 2)58 print_indented('</particDesc>', level + 1) # particDesc END59 # TODO: print genre Title here?60 # <textClass>61 # <keywords>62 # <term type="genreTitle">???</term>63 # </keywords>64 # </textClass>65 print_indented('</profileDesc>', level) # profileDesc END66def print_header_cast_single(xml_id, name, note=None, level=0):67 print_indented('<person xml:id="{}">'.format(xml_id), level)68 print_indented('<persName>{}</persName>'.format(name), level + 1)69 if note is not None:70 print_indented('<note>{}</note>'.format(note), level + 1)71 print_indented('</person>'.format(xml_id), level)72def print_text(data):73 print_indented('<text>', 1) # text BEGIN74 print_indented('<front>', 2) # front BEGIN75 76 # TODO: print docAuthor?77 # <docAuthor>???</docAuthor>78 # TODO: print docTitle?79 # <docTitle>80 # <titlePart type="main">???</titlePart>81 # </docTitle>82 print_text_cast(data, level=3)83 print_indented('</front>', 2) # front END84 # text end printed elsewhere85def print_text_cast(data, level):86 print_indented('<castList xml:id="{}">'.format(data["castList_id"]), level) # castList BEGIN87 # TODO: different structure of cast groups?88 print_indented('<castGroup>', level + 1)89 for character in data["cast"]:90 print_text_cast_single(character["name"], character["role"], character["cast_group"], level + 2)91 print_indented('</castGroup>', level + 1)92 print_indented('</castList>', level) # castList END93def print_text_cast_single(name, role=None, group=None, level=0):94 if group is not None and group:95 print_indented('<castItem n="{}"'.format(group), level)96 else:97 print_indented('<castItem>', level)98 99 print_indented('<role>', level + 1)100 print_indented('<name>{}</name>'.format(name), level + 2)101 print_indented('</role>', level + 1)102 if role is not None and role:103 print_indented('<roleDesc>{}</roleDesc>'.format(role), level + 1)104 print_indented('</castItem>', level)105def print_body_begin():106 print_indented('<body>', 2)107def print_act(i, name):108 if i > 1:109 print_indented('</div>', 4)110 print_indented('</div>', 3)111 112 #print_indented('<div type="act" n="{}" name="{}">'.format(i, name), 3)113 print_indented('<div type="act" n="{}">'.format(i), 3)114 print_indented('<head>{}</head>'.format(name), 4)115 print_indented('<div type="scene">', 4)116def print_body_end():117 print_indented('</div>', 4)118 print_indented('</div>', 3)119 print_indented('</body>', 2)120 print_indented('</text>', 1)121 print('</TEI>')122def print_utterance(utt, level=5):123 if utt is None or not utt:124 return125 if not utt["content"]:126 utt = None127 return128 # TODO: insert proper values into the ``who'' attribute129 print_indented('<sp who="{}">'.format(utt["name"].lower()), level) # sp BEGIN130 print_indented('<speaker>{}</speaker>'.format(utt["name"]), level + 1)131 for line in utt["content"]:132 if line: # skip empty lines133 print_indented('<l>{}</l>'.format(line), level + 1)134 print_indented('</sp>', level) # sp END135 utt = None136def main(args):137 data = {"cast" : [], "castList_id" : args.input_file.split("/")[-1].split("-")[0].lower() } # Dictionary containing the ``contents'' of the XML template138 cast_hash = {} # Hash for checking whether a keyword is a character in the play139 utterance = None # Used to ``buffer'' character utterances from the text140 n_act = 1141 header_printed = False # We only want to print the header once142 with open(args.input_file, 'r') as in_f:143 line_num = 1144 for line in in_f:145 line = line.strip()146 # Skip empty lines147 if not line:148 continue149 if line[0] == '^' or line[0] == '#':150 # Print header and the beginning of the body151 if not header_printed:152 print_header(data)153 print_text(data)154 print_body_begin()155 header_printed = True156 if line_num == 1:157 data["title"] = line158 elif line_num == 2:159 data["author"] = line160 elif line_num == 3:161 data["description"] = line162 elif line[0] == '*':163 line = line[2:].split(",")164 if len(line) != 3:165 raise ValueError(166 "Line ``* {}'' does not contain three entries "167 "separated by comma.".format(",".join(line)))168 character = {169 "name": line[0],170 "xml_id": "_".join(line[0].split(" ")).lower(),171 "role": line[1].strip(),172 "cast_group": line[2].strip(),173 }174 cast_hash[line[0]] = 1175 data["cast"].append(character)176 elif line[0] == '^': # Act indicator177 print_utterance(utterance)178 print_act(n_act, line[2:])179 n_act += 1180 elif line[0] == '!': # Act end indicator == do nothing?181 print_utterance(utterance)182 elif line[0] == "#": # Stage indicator183 if utterance is not None:184 name = utterance["name"]185 print_utterance(utterance)186 utterance = {"name": name, "content": []}187 print_indented('<stage>{}</stage>'.format(line[2:]), 5)188 elif ":" in line:189 print_utterance(utterance)190 name = line.split(":")[0]191 text = line.split(":")[1].strip()192 utterance = {"name": name, "content": [text]}193 elif utterance is not None:194 utterance["content"].append(line.strip())195 line_num += 1196 print_body_end()197 198def parse_args():199 parser = argparse.ArgumentParser(description=__doc__)200 parser.add_argument(201 "--input-file", type=str, required=True,...
IndentedList.py
Source:IndentedList.py
1#!/usr/bin/env python32# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.3# This program or module is free software: you can redistribute it and/or4# modify it under the terms of the GNU General Public License as published5# by the Free Software Foundation, either version 3 of the License, or6# (at your option) any later version. It is provided for educational7# purposes and is distributed in the hope that it will be useful, but8# WITHOUT ANY WARRANTY; without even the implied warranty of9# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU10# General Public License for more details.111213def indented_list_sort(indented_list, indent=" "):14 """Vrátà abecednÄ seÅazenou kopii zadaného seznamu1516 Seznam s odsazenÃm je sezanam ÅetÄzců v hierarchii odsazenÃ17 použité pro oznaÄenà podÅÃzených prkvů.18 Parametr indent stanovà znaky, které tvoÅà jednu úroveÅ odsazenÃ.1920 Funkce zkopÃruje seznam a vrátà jej abecednÄ seÅazenà bez oheldu na21 velikost pÃsmen s tÃm, že podÅÃzené prvky se seÅadÃ22 pod svými rodiÄi, což rekurzivnÄ pokraÄuje do libovolné hloubky.2324 >>> indented_list = ["M", " MX", " MG", "D", " DA", " DF",\25 " DFX", " DFK", " DFB", " DC", "K", "X", "H", " HJ",\26 " HB", "A"]27 >>> 28 >>> indented_list = indented_list_sort(indented_list, " ")29 >>> indented_list[:8]30 ['A', 'D', ' DA', ' DC', ' DF', ' DFB', ' DFK', ' DFX']31 >>> indented_list[8:]32 ['H', ' HB', ' HJ', 'K', 'M', ' MG', ' MX', 'X']33 """34 KEY, ITEM, CHILDREN = range(3)3536 def add_entry(level, key, item, children):37 if level == 0:38 children.append((key, item, []))39 else:40 add_entry(level - 1, key, item, children[-1][CHILDREN])4142 def update_indented_list(entry):43 indented_list.append(entry[ITEM])44 for subentry in sorted(entry[CHILDREN]):45 update_indented_list(subentry)4647 entries = []48 for item in indented_list:49 level = 050 i = 051 while item.startswith(indent, i):52 i += len(indent)53 level += 154 key = item.strip().lower()55 add_entry(level, key, item, entries)5657 indented_list = []58 for entry in sorted(entries):59 update_indented_list(entry)60 return indented_list616263def indented_list_sort_local(indented_list, indent=" "):64 """65 PÅi zadánà seznam s odsazenÃm, tj. seznamu prvků s odsazenými66 podprky, seÅadà tyto prvky a podprvky v rámci každého prvku67 (pÅi Äemž pokraÄuje rekurzivnÄ do hloubky) podle abecedy 68 bez ohledu na velikost pÃsmen.6970 >>> indented_list = ["M", " MX", " MG", "D", " DA", " DF", " DFX", \71 " DFK", " DFB", " DC", "K", "X", "H", " HJ", " HB", "A"]72 >>> 73 >>> indented_list = indented_list_sort_local(indented_list, " ")74 >>> indented_list[:8]75 ['A', 'D', ' DA', ' DC', ' DF', ' DFB', ' DFK', ' DFX']76 >>> indented_list[8:]77 ['H', ' HB', ' HJ', 'K', 'M', ' MG', ' MX', 'X']78 """79 KEY, ITEM, CHILDREN = range(3)8081 def add_entry(key, item, children):82 nonlocal level83 if level == 0:84 children.append((key, item, []))85 else:86 level -= 187 add_entry(key, item, children[-1][CHILDREN])8889 def update_indented_list(entry):90 indented_list.append(entry[ITEM])91 for subentry in sorted(entry[CHILDREN]):92 update_indented_list(subentry)9394 entries = []95 for item in indented_list:96 level = 097 i = 098 while item.startswith(indent, i):99 i += len(indent)100 level += 1101 key = item.strip().lower()102 add_entry(key, item, entries)103104 indented_list = []105 for entry in sorted(entries):106 update_indented_list(entry)107 return indented_list108109110if __name__ == "__main__":111 before = ["Nekovy",112 " VodÃk",113 " UhlÃk",114 " DusÃk",115 " KyslÃk",116 "PÅechodné prvky",117 " Lanthanoidy",118 " Cerium",119 " Europium",120 " Aktinoidy",121 " Uran",122 " Curium",123 " Plutonium",124 "Alkalické kovy",125 " Lithium",126 " SodÃk",127 " DraslÃk"]128 result1 = indented_list_sort(before)129 result2 = indented_list_sort_local(before)130 after = ["Alkalické kovy",131 " DraslÃk",132 " Lithium",133 " SodÃk",134 "Nekovy",135 " DusÃk",136 " KyslÃk",137 " UhlÃk",138 " VodÃk",139 "PÅechodné prvky",140 " Aktinoidy",141 " Curium",142 " Plutonium",143 " Uran",144 " Lanthanoidy",145 " Cerium",146 " Europium"]147 assert result1 == result2 == after148149 import doctest
...
mb_20030210.py
Source:mb_20030210.py
1from Xml.Xslt import test_harness2source_1 = """<?xml version="1.0" encoding="utf-8"?>3<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">4 <head>5 <title>Test</title>6 </head>7 <body>8 <h1>Test</h1>9 <p>XML Line 1<br/>XML Line 2<br xmlns=""/>XML Line 3 after HTML br</p>10 <script language="JavaScript">11 /*12 1 & 2 are < 3 but > 013 */14</script>15 <p xmlns="">HTML line 1<br/>HTML line 2<script language="JavaScript">16 /*17 1 & 2 are < 3 but > 018 */19</script></p>20 </body>21</html>"""22sheet_1 = """<xsl:transform23 version="1.0"24 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">25 <xsl:output method="html" indent="no"/>26 <xsl:strip-space elements="*"/>27 <xsl:template match="@*|node()">28 <xsl:copy>29 <xsl:apply-templates select="@*|node()"/>30 </xsl:copy>31 </xsl:template>32</xsl:transform>"""33sheet_2 = """<xsl:transform34 version="1.0"35 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">36 <xsl:output method="html" indent="yes"/>37 <xsl:strip-space elements="*"/>38 <xsl:template match="@*|node()">39 <xsl:copy>40 <xsl:apply-templates select="@*|node()"/>41 </xsl:copy>42 </xsl:template>43</xsl:transform>"""44# indent=no45expected_1 = """<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><title>Test</title></head><body><h1>Test</h1><p>XML Line 1<br/>XML Line 2<br xmlns="">XML Line 3 after HTML br</p><script language="JavaScript">46 /*47 1 & 2 are < 3 but > 048 */49</script><p xmlns="">HTML line 1<br>HTML line 2<script language="JavaScript">50 /*51 1 & 2 are < 3 but > 052 */53</script></p></body></html>"""54# indent=yes55expected_2 = """<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">56 <head>57 <title>Test</title>58 </head>59 <body>60 <h1>Test</h1>61 <p>XML Line 162 <br/>XML Line 263 <br xmlns="">XML Line 3 after HTML br64 </p>65 <script language="JavaScript">66 /*67 1 & 2 are < 3 but > 068 */69</script>70 <p xmlns="">HTML line 171 <br>HTML line 2<script language="JavaScript">72 /*73 1 & 2 are < 3 but > 074 */75</script></p>76 </body>77</html>"""78source_3 = """<?xml version="1.0"?><dummy/>"""79sheet_3 = """<?xml version="1.0" encoding="utf-8"?>80<xsl:stylesheet version="1.0"81 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">82 <xsl:output method="html" indent="yes"/>83 <xsl:template match="/">84 <html>85 <body>86 <h1>indented html</h1>87 <p>html indented 1 html indented 2 html indented 3</p>88 <div class="screen">89 <pre>html not indented 1 html not indented 2<span xmlns="http://foo/bar"><i><b>xml span, i, b, this text, br, p.i., not indented</b></i><br/><xsl:processing-instruction name="foo">bar</xsl:processing-instruction></span><p>still xml, no indenting here either</p>90 <span xmlns="">html not indented 3<br/><p>html still not indented</p> html on new line but still not indented</span>91 </pre>92 <p>html indented<span xmlns="http://foo/bar"><i><b>xml indented<pre xmlns="">html not indented 1 and 2</pre> back to xml indented</b></i></span>html indented again and again</p>93 </div>94 </body>95 </html>96 </xsl:template>97</xsl:stylesheet>"""98expected_3 = """<html>99 <body>100 <h1>indented html</h1>101 <p>html indented 1102html indented 2103html indented 3</p>104 <div class="screen">105 <pre>html not indented 1106html not indented 2<span xmlns="http://foo/bar"><i><b>xml span, i, b, this text, br, p.i., not indented</b></i><br/><?foo bar?></span><p>still xml, no indenting here either</p><span>html not indented 3<br><p>html still not indented</p>107html on new line but still not indented</span></pre>108 <p>html indented109 <span xmlns="http://foo/bar">110 <i>111 <b>xml indented<pre xmlns="">html not indented 1112and 2</pre> back to xml indented</b>113 </i>114 </span>html indented again115and again116 </p>117 </div>118 </body>119</html>"""120def Test(tester):121 source = test_harness.FileInfo(string=source_1)122 sheet = test_harness.FileInfo(string=sheet_1)123 test_harness.XsltTest(tester, source, [sheet], expected_1,124 title="mixed XML and HTML in HTML output; indent=no")125 source = test_harness.FileInfo(string=source_1)126 sheet = test_harness.FileInfo(string=sheet_2)127 test_harness.XsltTest(tester, source, [sheet], expected_2,128 title="mixed XML and HTML in HTML output; indent=yes")129 source = test_harness.FileInfo(string=source_3)130 sheet = test_harness.FileInfo(string=sheet_3)131 test_harness.XsltTest(tester, source, [sheet], expected_3,132 title="deeply mixed XML and HTML in HTML output; indent=yes")...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!