OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Unable to strip whitespace from a string using pyparsing set_parse_action()

  • Thread starter Thread starter Michael Henry
  • Start date Start date
M

Michael Henry

Guest
I've got a generic "text block" element, for which I copied the whitespace-stripping code from the documentation:

Code:
import pyparsing as pp

text_block = pp.Group(
    pp.OneOrMore(
        pp.SkipTo(pp.LineEnd()) + pp.LineEnd().suppress(),
        stopOn=pp.StringEnd() | (pp.LineStart() + (pp.Literal("E)") | pp.Literal("F)")))
    )
).set_parse_action(pp.token_map(str.strip))

Unfortunately this returns an error:

FAIL-EXCEPTION: TypeError: descriptor 'strip' for 'str' objects doesn't apply to a 'ParseResults' object

I replaced the use of token_map with a function:

Code:
def _strip_whitespace(tokens):
    return [token.str.strip() for token in tokens]

text_block = pp.Group(
    pp.OneOrMore(
        pp.SkipTo(pp.LineEnd()) + pp.LineEnd().suppress(),
        stopOn=pp.StringEnd() | (pp.LineStart() + (pp.Literal("E)") | pp.Literal("F)")))
    )
).set_parse_action(_strip_whitespace)

...but now it deletes all the text(!)
<p>I've got a generic "text block" element, for which I copied the whitespace-stripping code from the <a href="https://pyparsing-docs.readthedocs.io/en/latest/pyparsing.html" rel="nofollow noreferrer">documentation</a>:</p>
<pre><code>import pyparsing as pp

text_block = pp.Group(
pp.OneOrMore(
pp.SkipTo(pp.LineEnd()) + pp.LineEnd().suppress(),
stopOn=pp.StringEnd() | (pp.LineStart() + (pp.Literal("E)") | pp.Literal("F)")))
)
).set_parse_action(pp.token_map(str.strip))
</code></pre>
<p>Unfortunately this returns an error:</p>
<blockquote>
<p>FAIL-EXCEPTION: TypeError: descriptor 'strip' for 'str' objects
doesn't apply to a 'ParseResults' object</p>
</blockquote>
<p>I replaced the use of <code>token_map</code> with a function:</p>
<pre><code>def _strip_whitespace(tokens):
return [token.str.strip() for token in tokens]

text_block = pp.Group(
pp.OneOrMore(
pp.SkipTo(pp.LineEnd()) + pp.LineEnd().suppress(),
stopOn=pp.StringEnd() | (pp.LineStart() + (pp.Literal("E)") | pp.Literal("F)")))
)
).set_parse_action(_strip_whitespace)
</code></pre>
<p>...but now it deletes all the text(!)</p>
 

Latest posts

Top