⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test_sre.py

📁 mallet是自然语言处理、机器学习领域的一个开源项目。
💻 PY
📖 第 1 页 / 共 2 页
字号:
test(r"""pat.match('a').group(1, 2, 3)""", ('a', None, None))test(r"""pat.match('b').group('a1', 'b2', 'c3')""", (None, 'b', None))test(r"""pat.match('ac').group(1, 'b2', 3)""", ('a', None, 'c'))# bug 448951 (similar to 429357, but with single char match)# (Also test greedy matches.)for op in '','?','*':    test(r"""sre.match(r'((.%s):)?z', 'z').groups()"""%op, (None, None))    test(r"""sre.match(r'((.%s):)?z', 'a:z').groups()"""%op, ('a:', 'a'))if verbose:    print "Running tests on sre.escape"p = ""for i in range(0, 256):    p = p + chr(i)    test(r"""sre.match(sre.escape(chr(i)), chr(i)) is not None""", 1)    test(r"""sre.match(sre.escape(chr(i)), chr(i)).span()""", (0,1))pat = sre.compile(sre.escape(p))test(r"""pat.match(p) is not None""", 1)test(r"""pat.match(p).span()""", (0,256))if verbose:    print 'Running tests on sre.Scanner'def s_ident(scanner, token): return tokendef s_operator(scanner, token): return "op%s" % tokendef s_float(scanner, token): return float(token)def s_int(scanner, token): return int(token)scanner = sre.Scanner([    (r"[a-zA-Z_]\w*", s_ident),    (r"\d+\.\d*", s_float),    (r"\d+", s_int),    (r"=|\+|-|\*|/", s_operator),    (r"\s+", None),    ])# sanity checktest('scanner.scan("sum = 3*foo + 312.50 + bar")',     (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], ''))if verbose:    print 'Pickling a SRE_Pattern instance'try:    import pickle    pat = sre.compile(r'a(?:b|(c|e){1,2}?|d)+?(.)')    s = pickle.dumps(pat)    pat = pickle.loads(s)except:    print TestFailed, 're module pickle'try:    import cPickle    pat = sre.compile(r'a(?:b|(c|e){1,2}?|d)+?(.)')    s = cPickle.dumps(pat)    pat = cPickle.loads(s)except:    print TestFailed, 're module cPickle'# constantstest(r"""sre.I""", sre.IGNORECASE)test(r"""sre.L""", sre.LOCALE)test(r"""sre.M""", sre.MULTILINE)test(r"""sre.S""", sre.DOTALL)test(r"""sre.X""", sre.VERBOSE)test(r"""sre.T""", sre.TEMPLATE)test(r"""sre.U""", sre.UNICODE)for flags in [sre.I, sre.M, sre.X, sre.S, sre.L, sre.T, sre.U]:    try:        r = sre.compile('^pattern$', flags)    except:        print 'Exception raised on flag', flagsif verbose:    print 'Test engine limitations'# Try nasty case that overflows the straightforward recursive# implementation of repeated groups.test("sre.match('(x)*', 50000*'x').span()", (0, 50000), RuntimeError)test("sre.match(r'(x)*y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)test("sre.match(r'(x)*?y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)from re_tests import *if verbose:    print 'Running re_tests test suite'else:    # To save time, only run the first and last 10 tests    #tests = tests[:10] + tests[-10:]    passfor t in tests:    sys.stdout.flush()    pattern=s=outcome=repl=expected=None    if len(t)==5:        pattern, s, outcome, repl, expected = t    elif len(t)==3:        pattern, s, outcome = t    else:        raise ValueError, ('Test tuples should have 3 or 5 fields',t)    try:        obj=sre.compile(pattern)    except sre.error:        if outcome==SYNTAX_ERROR: pass  # Expected a syntax error        else:            print '=== Syntax error:', t    except KeyboardInterrupt: raise KeyboardInterrupt    except:        print '*** Unexpected error ***', t        if verbose:            traceback.print_exc(file=sys.stdout)    else:        try:            result=obj.search(s)        except (sre.error), msg:            print '=== Unexpected exception', t, repr(msg)        if outcome==SYNTAX_ERROR:            print '=== Compiled incorrectly', t        elif outcome==FAIL:            if result is None: pass   # No match, as expected            else: print '=== Succeeded incorrectly', t        elif outcome==SUCCEED:            if result is not None:                # Matched, as expected, so now we compute the                # result string and compare it to our expected result.                start, end = result.span(0)                vardict={'found': result.group(0),                         'groups': result.group(),                         'flags': result.re.flags}                for i in range(1, 100):                    try:                        gi = result.group(i)                        # Special hack because else the string concat fails:                        if gi is None:                            gi = "None"                    except IndexError:                        gi = "Error"                    vardict['g%d' % i] = gi                for i in result.re.groupindex.keys():                    try:                        gi = result.group(i)                        if gi is None:                            gi = "None"                    except IndexError:                        gi = "Error"                    vardict[i] = gi                repl=eval(repl, vardict)                if repl!=expected:                    print '=== grouping error', t,                    print repr(repl)+' should be '+repr(expected)            else:                print '=== Failed incorrectly', t                continue            # Try the match on a unicode string, and check that it            # still succeeds.            try:                u = unicode(s, "latin-1")            except NameError:                pass            except TypeError:                continue # skip unicode test strings            else:                result=obj.search(u)                if result==None:                    print '=== Fails on unicode match', t            # Try the match on a unicode pattern, and check that it            # still succeeds.            try:                u = unicode(pattern, "latin-1")            except NameError:                pass            else:                obj=sre.compile(u)                result=obj.search(s)                if result==None:                    print '=== Fails on unicode pattern match', t            # Try the match with the search area limited to the extent            # of the match and see if it still succeeds.  \B will            # break (because it won't match at the end or start of a            # string), so we'll ignore patterns that feature it.            if pattern[:2]!='\\B' and pattern[-2:]!='\\B':                obj=sre.compile(pattern)                result=obj.search(s, result.start(0), result.end(0)+1)                if result==None:                    print '=== Failed on range-limited match', t            # Try the match with IGNORECASE enabled, and check that it            # still succeeds.            obj=sre.compile(pattern, sre.IGNORECASE)            result=obj.search(s)            if result==None:                print '=== Fails on case-insensitive match', t            # Try the match with LOCALE enabled, and check that it            # still succeeds.            obj=sre.compile(pattern, sre.LOCALE)            result=obj.search(s)            if result==None:                print '=== Fails on locale-sensitive match', t            # Try the match with UNICODE locale enabled, and check            # that it still succeeds.            if have_unicode:                obj=sre.compile(pattern, sre.UNICODE)                result=obj.search(s)                if result==None:                    print '=== Fails on unicode-sensitive match', t

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -