• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python compat.str函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mwparserfromhell.compat.str函数的典型用法代码示例。如果您正苦于以下问题:Python str函数的具体用法?Python str怎么用?Python str使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了str函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_unicode

 def test_unicode(self):
     """test Template.__unicode__()"""
     node = Template(wraptext("foobar"))
     self.assertEqual("{{foobar}}", str(node))
     node2 = Template(wraptext("foo"),
                      [pgenh("1", "bar"), pgens("abc", "def")])
     self.assertEqual("{{foo|bar|abc=def}}", str(node2))
开发者ID:JonathanRaiman,项目名称:mwparserfromhell,代码行数:7,代码来源:test_template.py


示例2: test_get

    def test_get(self):
        """test Tag.get()"""
        attrs = [agen("name", "foo")]
        node = Tag(wraptext("ref"), wraptext("cite"), attrs)
        self.assertIs(attrs[0], node.get("name"))
        self.assertIs(attrs[0], node.get("  name  "))
        self.assertIs(attrs[0], node.get(wraptext("name")))
        self.assertRaises(ValueError, node.get, "Name")
        self.assertRaises(ValueError, node.get, "foo")

        attrs = [
            agen("id", "foo"),
            agenp("class", "bar", "  ", "\n", "\n"),
            agen("foo", "bar"),
            agenpnv("foo", " ", "  \n ", " \t"),
        ]
        node2 = Tag(wraptext("div"), attrs=attrs, self_closing=True)
        self.assertIs(attrs[0], node2.get("id"))
        self.assertIs(attrs[1], node2.get("class"))
        self.assertIs(attrs[1], node2.get(attrs[1].pad_first + str(attrs[1].name) + attrs[1].pad_before_eq))
        self.assertIs(attrs[3], node2.get(attrs[3]))
        self.assertIs(attrs[3], node2.get(str(attrs[3])))
        self.assertIs(attrs[3], node2.get(" foo"))
        self.assertRaises(ValueError, node2.get, "idclass")
        self.assertRaises(ValueError, node2.get, "id class")
        self.assertRaises(ValueError, node2.get, "id=foo")
开发者ID:vedmaka,项目名称:ipc-parser,代码行数:26,代码来源:test_tag.py


示例3: _load_tests

    def _load_tests(cls, filename, name, text, restrict=None):
        """Load all tests in *text* from the file *filename*."""
        tests = text.split("\n---\n")
        counter = 1
        digits = len(str(len(tests)))
        for test in tests:
            data = {"name": None, "label": None, "input": None, "output": None}
            try:
                cls._parse_test(test, data)
            except _TestParseError as err:
                if data["name"]:
                    error = "Could not parse test '{0}' in '{1}':\n\t{2}"
                    print(error.format(data["name"], filename, err))
                else:
                    error = "Could not parse a test in '{0}':\n\t{1}"
                    print(error.format(filename, err))
                continue

            if not data["name"]:
                error = "A test in '{0}' was ignored because it lacked a name"
                print(error.format(filename))
                continue
            if data["input"] is None or data["output"] is None:
                error = "Test '{0}' in '{1}' was ignored because it lacked an input or an output"
                print(error.format(data["name"], filename))
                continue

            number = str(counter).zfill(digits)
            counter += 1
            if restrict and data["name"] != restrict:
                continue

            fname = "test_{0}{1}_{2}".format(name, number, data["name"])
            meth = cls._build_test_method(fname, data)
            setattr(cls, fname, meth)
开发者ID:HazardSJ,项目名称:mwparserfromhell,代码行数:35,代码来源:_test_tokenizer.py


示例4: test_unicode

 def test_unicode(self):
     """test HTMLEntity.__unicode__()"""
     node1 = HTMLEntity("nbsp", named=True, hexadecimal=False)
     node2 = HTMLEntity("107", named=False, hexadecimal=False)
     node3 = HTMLEntity("6b", named=False, hexadecimal=True)
     node4 = HTMLEntity("6C", named=False, hexadecimal=True, hex_char="X")
     self.assertEqual(" ", str(node1))
     self.assertEqual("k", str(node2))
     self.assertEqual("k", str(node3))
     self.assertEqual("l", str(node4))
开发者ID:earwig,项目名称:mwparserfromhell,代码行数:10,代码来源:test_html_entity.py


示例5: test_unicode

    def test_unicode(self):
        """test Tag.__unicode__()"""
        node1 = Tag(wraptext("ref"))
        node2 = Tag(wraptext("span"), wraptext("foo"),
                    [agen("style", "color: red;")])
        node3 = Tag(wraptext("ref"),
                    attrs=[agennq("name", "foo"),
                           agenpnv("some_attr", "   ", "", "")],
                    self_closing=True)
        node4 = Tag(wraptext("br"), self_closing=True, padding=" ")
        node5 = Tag(wraptext("br"), self_closing=True, implicit=True)
        node6 = Tag(wraptext("br"), self_closing=True, invalid=True,
                    implicit=True)
        node7 = Tag(wraptext("br"), self_closing=True, invalid=True,
                    padding=" ")
        node8 = Tag(wraptext("hr"), wiki_markup="----", self_closing=True)
        node9 = Tag(wraptext("i"), wraptext("italics!"), wiki_markup="''")

        self.assertEqual("<ref></ref>", str(node1))
        self.assertEqual('<span style="color: red;">foo</span>', str(node2))
        self.assertEqual("<ref name=foo   some_attr/>", str(node3))
        self.assertEqual("<br />", str(node4))
        self.assertEqual("<br>", str(node5))
        self.assertEqual("</br>", str(node6))
        self.assertEqual("</br />", str(node7))
        self.assertEqual("----", str(node8))
        self.assertEqual("''italics!''", str(node9))
开发者ID:earwig,项目名称:mwparserfromhell,代码行数:27,代码来源:test_tag.py


示例6: test_unicode

 def test_unicode(self):
     """test ExternalLink.__unicode__()"""
     node = ExternalLink(wraptext("http://example.com/"), brackets=False)
     self.assertEqual("http://example.com/", str(node))
     node2 = ExternalLink(wraptext("http://example.com/"))
     self.assertEqual("[http://example.com/]", str(node2))
     node3 = ExternalLink(wraptext("http://example.com/"), wrap([]))
     self.assertEqual("[http://example.com/ ]", str(node3))
     node4 = ExternalLink(wraptext("http://example.com/"),
                          wraptext("Example Web Page"))
     self.assertEqual("[http://example.com/ Example Web Page]", str(node4))
开发者ID:HazardSJ,项目名称:mwparserfromhell,代码行数:11,代码来源:test_external_link.py


示例7: test_brackets

 def test_brackets(self):
     """test getter/setter for the brackets attribute"""
     node1 = ExternalLink(wraptext("http://example.com/"), brackets=False)
     node2 = ExternalLink(wraptext("http://example.com/"), wraptext("Link"))
     self.assertFalse(node1.brackets)
     self.assertTrue(node2.brackets)
     node1.brackets = True
     node2.brackets = False
     self.assertTrue(node1.brackets)
     self.assertFalse(node2.brackets)
     self.assertEqual("[http://example.com/]", str(node1))
     self.assertEqual("http://example.com/", str(node2))
开发者ID:HazardSJ,项目名称:mwparserfromhell,代码行数:12,代码来源:test_external_link.py


示例8: test_unicode

 def test_unicode(self):
     """test Attribute.__unicode__()"""
     node = Attribute(wraptext("foo"))
     self.assertEqual(" foo", str(node))
     node2 = Attribute(wraptext("foo"), wraptext("bar"))
     self.assertEqual(' foo="bar"', str(node2))
     node3 = Attribute(wraptext("a"), wraptext("b"), True, "", " ", "   ")
     self.assertEqual('a =   "b"', str(node3))
     node3 = Attribute(wraptext("a"), wraptext("b"), False, "", " ", "   ")
     self.assertEqual("a =   b", str(node3))
     node4 = Attribute(wraptext("a"), wrap([]), False, " ", "", " ")
     self.assertEqual(" a= ", str(node4))
开发者ID:Mdann52,项目名称:mwparserfromhell,代码行数:12,代码来源:test_attribute.py


示例9: test_types

    def test_types(self):
        """make sure StringMixIns convert to different types correctly"""
        fstr = _FakeString("fake string")
        self.assertEqual(str(fstr), "fake string")
        self.assertEqual(bytes(fstr), b"fake string")
        if py3k:
            self.assertEqual(repr(fstr), "'fake string'")
        else:
            self.assertEqual(repr(fstr), b"u'fake string'")

        self.assertIsInstance(str(fstr), str)
        self.assertIsInstance(bytes(fstr), bytes)
        if py3k:
            self.assertIsInstance(repr(fstr), str)
        else:
            self.assertIsInstance(repr(fstr), bytes)
开发者ID:stanta,项目名称:ipc-parser-1,代码行数:16,代码来源:test_string_mixin.py


示例10: _load_tests

 def _load_tests(cls, filename, name, text):
     """Load all tests in *text* from the file *filename*."""
     tests = text.split("\n---\n")
     counter = 1
     digits = len(str(len(tests)))
     for test in tests:
         data = {"name": None, "label": None, "input": None, "output": None}
         try:
             for line in test.strip().splitlines():
                 if line.startswith("name:"):
                     data["name"] = line[len("name:") :].strip()
                 elif line.startswith("label:"):
                     data["label"] = line[len("label:") :].strip()
                 elif line.startswith("input:"):
                     raw = line[len("input:") :].strip()
                     if raw[0] == '"' and raw[-1] == '"':
                         raw = raw[1:-1]
                     raw = raw.encode("raw_unicode_escape")
                     data["input"] = raw.decode("unicode_escape")
                 elif line.startswith("output:"):
                     raw = line[len("output:") :].strip()
                     try:
                         data["output"] = eval(raw, vars(tokens))
                     except Exception as err:
                         raise _TestParseError(err)
         except _TestParseError as err:
             if data["name"]:
                 error = "Could not parse test '{0}' in '{1}':\n\t{2}"
                 print(error.format(data["name"], filename, err))
             else:
                 error = "Could not parse a test in '{0}':\n\t{1}"
                 print(error.format(filename, err))
             continue
         if not data["name"]:
             error = "A test in '{0}' was ignored because it lacked a name"
             print(error.format(filename))
             continue
         if data["input"] is None or data["output"] is None:
             error = "Test '{0}' in '{1}' was ignored because it lacked an input or an output"
             print(error.format(data["name"], filename))
             continue
         number = str(counter).zfill(digits)
         fname = "test_{0}{1}_{2}".format(name, number, data["name"])
         meth = cls._build_test_method(fname, data)
         setattr(cls, fname, meth)
         counter += 1
开发者ID:JonathanRaiman,项目名称:mwparserfromhell,代码行数:46,代码来源:_test_tokenizer.py


示例11: inner

 def inner(self):
     if hasattr(self, "roundtrip"):
         expected = data["input"]
         actual = str(Builder().build(data["output"][:]))
     else:
         expected = data["output"]
         actual = self.tokenizer().tokenize(data["input"])
     self.assertEqual(expected, actual)
开发者ID:JonathanRaiman,项目名称:mwparserfromhell,代码行数:8,代码来源:_test_tokenizer.py


示例12: test_contains

 def test_contains(self):
     """test Wikicode.contains()"""
     code = parse("Here is {{aaa|{{bbb|xyz{{ccc}}}}}} and a [[page|link]]")
     tmpl1, tmpl2, tmpl3 = code.filter_templates()
     tmpl4 = parse("{{ccc}}").filter_templates()[0]
     self.assertTrue(code.contains(tmpl1))
     self.assertTrue(code.contains(tmpl3))
     self.assertFalse(code.contains(tmpl4))
     self.assertTrue(code.contains(str(tmpl4)))
     self.assertTrue(code.contains(tmpl2.params[0].value))
开发者ID:earwig,项目名称:mwparserfromhell,代码行数:10,代码来源:test_wikicode.py


示例13: test_has

    def test_has(self):
        """test Tag.has()"""
        node = Tag(wraptext("ref"), wraptext("cite"), [agen("name", "foo")])
        self.assertTrue(node.has("name"))
        self.assertTrue(node.has("  name  "))
        self.assertTrue(node.has(wraptext("name")))
        self.assertFalse(node.has("Name"))
        self.assertFalse(node.has("foo"))

        attrs = [agen("id", "foo"), agenp("class", "bar", "  ", "\n", "\n"),
                 agen("foo", "bar"), agenpnv("foo", " ", "  \n ", " \t")]
        node2 = Tag(wraptext("div"), attrs=attrs, self_closing=True)
        self.assertTrue(node2.has("id"))
        self.assertTrue(node2.has("class"))
        self.assertTrue(node2.has(attrs[1].pad_first + str(attrs[1].name) +
                                  attrs[1].pad_before_eq))
        self.assertTrue(node2.has(attrs[3]))
        self.assertTrue(node2.has(str(attrs[3])))
        self.assertFalse(node2.has("idclass"))
        self.assertFalse(node2.has("id class"))
        self.assertFalse(node2.has("id=foo"))
开发者ID:earwig,项目名称:mwparserfromhell,代码行数:21,代码来源:test_tag.py


示例14: test_unicode

 def test_unicode(self):
     """test Attribute.__unicode__()"""
     node = Attribute(wraptext("foo"))
     self.assertEqual(" foo", str(node))
     node2 = Attribute(wraptext("foo"), wraptext("bar"))
     self.assertEqual(' foo="bar"', str(node2))
     node3 = Attribute(wraptext("a"), wraptext("b"), '"', "", " ", "   ")
     self.assertEqual('a =   "b"', str(node3))
     node4 = Attribute(wraptext("a"), wraptext("b"), "'", "", " ", "   ")
     self.assertEqual("a =   'b'", str(node4))
     node5 = Attribute(wraptext("a"), wraptext("b"), None, "", " ", "   ")
     self.assertEqual("a =   b", str(node5))
     node6 = Attribute(wraptext("a"), wrap([]), None, " ", "", " ")
     self.assertEqual(" a= ", str(node6))
开发者ID:earwig,项目名称:mwparserfromhell,代码行数:14,代码来源:test_attribute.py


示例15: test_readme_4

 def test_readme_4(self):
     """test a block of example code in the README"""
     text = "{{cleanup}} '''Foo''' is a [[bar]]. {{uncategorized}}"
     code = mwparserfromhell.parse(text)
     for template in code.filter_templates():
         if template.name.matches("Cleanup") and not template.has("date"):
             template.add("date", "July 2012")
     res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{uncategorized}}"
     self.assertPrint(code, res)
     code.replace("{{uncategorized}}", "{{bar-stub}}")
     res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
     self.assertPrint(code, res)
     if py3k:
         res = "['{{cleanup|date=July 2012}}', '{{bar-stub}}']"
     else:
         res = "[u'{{cleanup|date=July 2012}}', u'{{bar-stub}}']"
     self.assertPrint(code.filter_templates(), res)
     text = str(code)
     res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
     self.assertPrint(text, res)
     self.assertEqual(text, code)
开发者ID:JonathanRaiman,项目名称:mwparserfromhell,代码行数:21,代码来源:test_docs.py


示例16: test_unicode

 def test_unicode(self):
     """test Text.__unicode__()"""
     node = Text("foobar")
     self.assertEqual("foobar", str(node))
     node2 = Text("f贸贸bar")
     self.assertEqual("f贸贸bar", str(node2))
开发者ID:earwig,项目名称:mwparserfromhell,代码行数:6,代码来源:test_text.py


示例17: test_unicode

 def test_unicode(self):
     """test Wikicode.__unicode__()"""
     code1 = parse("foobar")
     code2 = parse("Have a {{template}} and a [[page|link]]")
     self.assertEqual("foobar", str(code1))
     self.assertEqual("Have a {{template}} and a [[page|link]]", str(code2))
开发者ID:stanta,项目名称:ipc-parser-1,代码行数:6,代码来源:test_wikicode.py


示例18: test_unicode

 def test_unicode(self):
     """test Heading.__unicode__()"""
     node = Heading(wraptext("foobar"), 2)
     self.assertEqual("==foobar==", str(node))
     node2 = Heading(wraptext(" zzz "), 5)
     self.assertEqual("===== zzz =====", str(node2))
开发者ID:Mdann52,项目名称:mwparserfromhell,代码行数:6,代码来源:test_heading.py


示例19: test_formatting

    def test_formatting(self):
        """test realistic param manipulation with complex whitespace formatting
        (assumes that parsing works correctly)"""
        tests = [
    # https://en.wikipedia.org/w/index.php?title=Lamar_County,_Georgia&oldid=792356004
    ("""{{Infobox U.S. county
| county = Lamar County
| state = Georgia
| seal =
| founded = 1920
| seat wl = Barnesville
| largest city wl = Barnesville
| area_total_sq_mi = 186
| area_land_sq_mi = 184
| area_water_sq_mi = 2.3
| area percentage = 1.3%
| census yr = 2010
| pop = 18317
| density_sq_mi = 100
| time zone = Eastern
| footnotes =
| web = www.lamarcountyga.com
| ex image = Lamar County Georgia Courthouse.jpg
| ex image cap = Lamar County courthouse in Barnesville
| district = 3rd
| named for = [[Lucius Quintus Cincinnatus Lamar II]]
}}""",
    """@@ -11,4 +11,4 @@
 | area percentage = 1.3%
-| census yr = 2010
-| pop = 18317
+| census estimate yr = 2016
+| pop = 12345<ref>example ref</ref>
 | density_sq_mi = 100"""),

    # https://en.wikipedia.org/w/index.php?title=Rockdale_County,_Georgia&oldid=792359760
    ("""{{Infobox U.S. County|
 county = Rockdale County |
 state = Georgia |
 seal =  |
 founded = October 18, 1870 |
 seat wl = Conyers |
 largest city wl = Conyers |
 area_total_sq_mi = 132 |
 area_land_sq_mi = 130 |
 area_water_sq_mi = 2.3 |
 area percentage = 1.7% |
 census yr = 2010|
 pop = 85215 |
 density_sq_mi = 657 |
 web = www.rockdalecounty.org
| ex image = Rockdale-county-courthouse.jpg
| ex image cap = Rockdale County Courthouse in Conyers
| district = 4th
| time zone= Eastern
}}""",
    """@@ -11,4 +11,4 @@
  area percentage = 1.7% |
- census yr = 2010|
- pop = 85215 |
+ census estimate yr = 2016 |
+ pop = 12345<ref>example ref</ref> |
  density_sq_mi = 657 |"""),

    # https://en.wikipedia.org/w/index.php?title=Spalding_County,_Georgia&oldid=792360413
    ("""{{Infobox U.S. County|
| county = Spalding County |
| state = Georgia |
| seal =  |
| founded = 1851 |
| seat wl = Griffin |
| largest city wl = Griffin |
| area_total_sq_mi = 200 |
| area_land_sq_mi = 196 |
| area_water_sq_mi = 3.1 |
| area percentage = 1.6% |
| census yr = 2010|
| pop = 64073 |
| density_sq_mi = 326 |
| web = www.spaldingcounty.com |
| named for = [[Thomas Spalding]]
| ex image = Spalding County Courthouse (NE corner).JPG
| ex image cap = Spalding County Courthouse in Griffin
| district = 3rd
| time zone = Eastern
}}""",
    """@@ -11,4 +11,4 @@
 | area percentage = 1.6% |
-| census yr = 2010|
-| pop = 64073 |
+|
+| census estimate yr = 2016 | pop = 12345<ref>example ref</ref> |
 | density_sq_mi = 326 |"""),

    # https://en.wikipedia.org/w/index.php?title=Clinton_County,_Illinois&oldid=794694648
    ("""{{Infobox U.S. county
 |county  = Clinton County
 |state = Illinois
| ex image           = File:Clinton County Courthouse, Carlyle.jpg
| ex image cap       = [[Clinton County Courthouse (Illinois)|Clinton County Courthouse]]
#.........这里部分代码省略.........
开发者ID:earwig,项目名称:mwparserfromhell,代码行数:101,代码来源:test_template.py


示例20: test_unicode

 def test_unicode(self):
     """test Parameter.__unicode__()"""
     node = Parameter(wraptext("1"), wraptext("foo"), showkey=False)
     self.assertEqual("foo", str(node))
     node2 = Parameter(wraptext("foo"), wraptext("bar"))
     self.assertEqual("foo=bar", str(node2))
开发者ID:Mdann52,项目名称:mwparserfromhell,代码行数:6,代码来源:test_parameter.py



注:本文中的mwparserfromhell.compat.str函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python nodes.Tag类代码示例发布时间:2022-05-27
下一篇:
Python mwparserfromhell.parse函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap