pytracery icon indicating copy to clipboard operation
pytracery copied to clipboard

Passing parameters containing commas

Open psychemedia opened this issue 7 years ago • 1 comments

If I pass a sentence containing commas in to a modifier, the params are split on simple commas:

rules={
    'origin': '''here's my sentence: #test.uppercase.echo(this is, my sentence, "with a comma, ok?")#''',
    'test': 'Ping'
}

def myecho(*params):
    return '::'.join(params)

grammar_test= {
    'echo': myecho
}

grammar = tracery.Grammar(rules)
grammar.add_modifiers(base_english)
grammar.add_modifiers(grammar_test)
print(grammar.flatten("#origin#"))

here's my sentence: PING::this is:: my sentence:: "with a comma:: ok?"

It would be useful to be able to pass in strings containing commas:

e.g.

import shlex

line='This is, a line, "with a comma, ok?"'
shlex.split(line)
['This', 'is,', 'a', 'line,', 'with a comma, ok?']

rather than:

line.split(',')
['This is', ' a line', ' "with a comma', ' ok?"']

psychemedia avatar Mar 07 '18 09:03 psychemedia

Here's a better approach...

import csv

def parse_params(txt):
    return [i for i in csv.reader([txt], skipinitialspace=True)][0]

(or maybe i.strip() for i...?)

Then in Node.expand() use parse_params(matches[0]) rather than matches[0].split(",") and in NodeAction.activate() use parse_params(self.rule)rather than self.rule.split(",") ?

psychemedia avatar May 06 '18 13:05 psychemedia