pyfil icon indicating copy to clipboard operation
pyfil copied to clipboard

strange syntax error

Open al-zatv opened this issue 5 years ago • 3 comments
trafficstars

Hello!

Let say I want to calculate frequencies of words in text, and show them in sorted order with their counts. Like:

Input: a b a c a d a d d Output: a 4, d 3, b 1, c 1

I do it this way: $ pyfil -s -l -x 'for ph in f: d[ph]=1+d.get(ph,0)' -e 'for ph in sorted(d, key=d.get)): print(ph,d[ph])'

But, I see an error SyntaxError: invalid syntax (, line 1)

What is wrong here?

al-zatv avatar Jun 19 '20 13:06 al-zatv

The tricky thing is here is that the argument of -e always has to be an expression so it can be printed.

Here's one way to do what you're trying to do:

$ echo "a b a c a d
a d d" | pyfil -s -l -x 'for ph in f: d[ph]=1+d.get(ph,0)' -e 'pair for pair in sorted(d.items(), key=lambda kv: kv[1])'
["b", 1]
["c", 1]
["d", 3]
["a", 4]

When the expression for printing is an iterator (i.e. a lazy iterable) like the generator expression above, it will print each value on a line.

In this specific case, it's easier to simply use a collections.Counter

> echo "a b a c a d
a d d" | pyfil -s -l -x -b "c = collections.Counter()" "c.update(f)" -e "iter(c.most_common())" 
["a", 4]
["d", 3]
["b", 1]
["c", 1]

ninjaaron avatar Jun 19 '20 15:06 ninjaaron

Thank you for explanation and workaround. But,generally speaking, I don't like that generator expressions stuff. Because sometimes instead of simply doing what I want to do, I spend time thinking how to solve that logical puzzle which came from tricky python's syntax. I think it may be more convinient to have an option to write usual python's code in final section, just like in main section. But, it is not necessary, of course.

al-zatv avatar Jun 27 '20 19:06 al-zatv

I'm currently refactoring pyfil to fit my current tastes in code style, and I will keep this feature request in mind.

One of my favorite qualities of pyfil is that it is expression-oriented and tends towards a functional way of expressing computation. However, the feature you're requesting should be simple to implement by simply adding an extra flag, and I don't think it's an unreasonable request.

On the other hand, I do think some of what you're wanting to do sounds like it's near the border where it should just be done in a script or interactively in the REPL---but if you find it practical to use pyfil in this way, I have no problem supporting it.

ninjaaron avatar Jun 29 '20 13:06 ninjaaron