Extension to :class:`scanString`, to modify matching text with modified tokens that may be returned from a parse action. To use ``transformString``, define a grammar and attach a parse action to it that modifies the returned token list. Invoking ``transformString()`
( self, instring )
| 1888 | raise exc |
| 1889 | |
| 1890 | def transformString( self, instring ): |
| 1891 | """ |
| 1892 | Extension to :class:`scanString`, to modify matching text with modified tokens that may |
| 1893 | be returned from a parse action. To use ``transformString``, define a grammar and |
| 1894 | attach a parse action to it that modifies the returned token list. |
| 1895 | Invoking ``transformString()`` on a target string will then scan for matches, |
| 1896 | and replace the matched text patterns according to the logic in the parse |
| 1897 | action. ``transformString()`` returns the resulting transformed string. |
| 1898 | |
| 1899 | Example:: |
| 1900 | |
| 1901 | wd = Word(alphas) |
| 1902 | wd.setParseAction(lambda toks: toks[0].title()) |
| 1903 | |
| 1904 | print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) |
| 1905 | |
| 1906 | prints:: |
| 1907 | |
| 1908 | Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. |
| 1909 | """ |
| 1910 | out = [] |
| 1911 | lastE = 0 |
| 1912 | # force preservation of <TAB>s, to minimize unwanted transformation of string, and to |
| 1913 | # keep string locs straight between transformString and scanString |
| 1914 | self.keepTabs = True |
| 1915 | try: |
| 1916 | for t,s,e in self.scanString( instring ): |
| 1917 | out.append( instring[lastE:s] ) |
| 1918 | if t: |
| 1919 | if isinstance(t,ParseResults): |
| 1920 | out += t.asList() |
| 1921 | elif isinstance(t,list): |
| 1922 | out += t |
| 1923 | else: |
| 1924 | out.append(t) |
| 1925 | lastE = e |
| 1926 | out.append(instring[lastE:]) |
| 1927 | out = [o for o in out if o] |
| 1928 | return "".join(map(_ustr,_flatten(out))) |
| 1929 | except ParseBaseException as exc: |
| 1930 | if ParserElement.verbose_stacktrace: |
| 1931 | raise |
| 1932 | else: |
| 1933 | # catch and re-raise exception from here, clears out pyparsing internal stack trace |
| 1934 | raise exc |
| 1935 | |
| 1936 | def searchString( self, instring, maxMatches=_MAX_INT ): |
| 1937 | """ |
no test coverage detected