r/Python • • Apr 04 '20

I Made This I'm a non-native English speaker and when watching podcasts/movies very often I find myself googling definition of a word so I wrote a very simple command line tool in python to make the process a little bit quicker

1.1k Upvotes

109 comments sorted by

44

u/[deleted] Apr 04 '20

if anyone is interested in the source code: https://github.com/gigamarr/smartsnek

91

u/isarl Apr 04 '20
#!/usr/bin/python

I saw this at the top of __main__.py – it is almost always better practice to write,

#!/usr/bin/env python3

You should never specify /usr/bin/python unless you really know what you're doing and have a good reason to do it. If you think you know what you're doing and you have a case for it, you are probably wrong. And you should never choose python over python2 or python3 unless you are specifically writing code that will run on either one – also very rare.

The reason we choose /usr/bin/env python3 over /usr/bin/python3 is that the Python binary may not be where you think it is – but no matter where it is, env will be able to find the right one. And it is very common, with Python, to want to use Python binaries that are not located at /usr/bin/python (nor even /usr/bin/python3).

37

u/[deleted] Apr 04 '20

Thank you, I didn't know the information you just gave me, I'll be mindful of that in future.

20

u/isarl Apr 04 '20

I think it's great you made this simple tool as a fun project. It looks like it does a great job at what you made it to do. I'm still looking at your code so if I see any other improvements to suggest, I'll let you know. :) I hope you keep learning and coding!

11

u/isarl Apr 04 '20

This is a nitpick, not as useful as my advice above, so weight it accordingly:
Based on your program output, it looks like your definitions already begin and end with newlines, so it seems to me that near the very bottom of smartsnek.py, when you do {" ".join(self.definitions)}, it makes as much sense to do {"".join(self.definitions)}.

This is still nitpicking, but it's more useful nitpicking:
In your definitions method, you write a list comprehension iterating over: for i in enumerate(...) and then you use i[0] to reference the index/enumeration, and i[1] to reference the enumerated value. You can simplify this with a Python feature called tuple-unpacking. The short version is that since enumerate returns a sequence of tuples, you can assign each part of the tuple to a local variable like so: for index, definition in enumerate(...) and then wherever you had previously typed i[0] you can replace it with index, and likewise you can replace i[1] with definition.

We could probably get into more details about error handling or argument parsing but I think this is a pretty good stopping point for now – and for the simplicity of the arguments you pass, honestly, importing argparse is probably overkill. :)

7

u/aufstand Apr 04 '20

Have you heard of click?

1

u/isarl Apr 04 '20

Thanks for the recommendation. Argparse is nice because it's in the standard library, but I'll keep that in mind… sometimes fighting with argparse to do exactly what I want is a bit much.

1

u/Weatherstation Apr 04 '20

That looks cool. I'll have to check it out for my next command line tool that requires input.

Though, I rarely write tools that require interactive user input anymore. Everything should be able to be defined with a arg/option flag when possible.

Automate everything.

4

u/mauledbyakodiak Apr 04 '20

The wording of the comment you're replying to may have not been the best, but also stating python3 vs python is better because the python variable isn't always pointing to python3. I believe for a long time it was pointing to python2 and then Arch changed their standard from python2 to python3 and that broke a bunch of stuff... supposedly.

8

u/xorvtec Apr 04 '20

I always recommend using argparse over sys.argv. Also check out the requests library in place of the older urllib.

0

u/aufstand Apr 04 '20

Kick argparse over https://click.palletsprojects.com/ :-)

5

u/irrelevantPseudonym Apr 04 '20

Click is nice but the benefit of using only the standard library shouldn't be underrated.

4

u/[deleted] Apr 04 '20

Too featureful. Argparse is simple, flexible, and well thought out.

1

u/FancyASlurpie Apr 04 '20

i prefer docopt, but each to their own.

2

u/[deleted] Apr 04 '20

Sure, but these libraries like click which are designed to build a whole UI aren't a drop-in replacement for argument handling libraries is my point.

0

u/FancyASlurpie Apr 04 '20

I'm not sure i see much of a difference between click, docopt and argparse. They're all pretty much targetted at writing CLI tools and thats about it. They just give you different ways to describe the arguments/helptext but the outcome is the same. Maybe im missing something?

1

u/[deleted] Apr 05 '20

OK well if you'd use them all you'd see.

1

u/FancyASlurpie Apr 05 '20 edited Apr 05 '20

Decided to do what you said and go try them out, maybe this example is too simple to see what you're talking about in terms of click being too featureful, but to me they all seem basically interchangeable and just a matter of personal preference.

Click - uses combination of decorators and comment strings to build up the cli argument validation and help text.

Docopt - uses comment strings to create the cli argument validation and help text.

Argparse - Create an object and build up arguments by calling functions on that object, helptext is generated by adding to the function calls.

https://github.com/FancyASlurpie/smartsnek_with_cli_libs

→ More replies (0)

1

u/pvkooten Apr 05 '20

guys, please check out the new kid on the block: https://github.com/kootenpv/cliche

announcing it tomorrow but you can have a sneak (or snake) peek

Instead of having to learn argparse or click, there is nothing to learn as it just uses types/default values/documentation to generate an argparse - just annotate a function using @cli

2

u/Weatherstation Apr 04 '20

You should use #!/usr/bin/env python (not python3), assuming the code is backwards compatible, because env will properly link to python3 if it's installed on the system.

2

u/CeeMX Apr 05 '20

Using /usr/bin/env also allows usage with a virtual environment. The other one doesn’t.

2

u/[deleted] Apr 04 '20

plus if you make the file executable, you wont have to type "python3" at the command line, just the name of the script.

1

u/mrdougan Apr 04 '20

Was just going ask for a link

148

u/eloydrummerboy Apr 04 '20

What I would do it have the program go into a loop, waiting for input. When you type in a word, it finds the definition, then waits for input again. It will quit if you type "quit" or "exit".

This way you don't have to type "python program-name word" each time. You just type "word".

If you're doing this often with podcasts, this might allow you to quickly look it up without having to stop.

7

u/[deleted] Apr 04 '20

That's a pretty good idea, you could have it running on a dropdown terminal/scratchpad and you can quickly bring it up if need be. I'll definitely add that functionality.

135

u/ThaiJohnnyDepp Apr 04 '20

But what if you wanted to look up the definition of "exit" or "quit" 😭

123

u/eloydrummerboy Apr 04 '20

Forbidden knowledge.

66

u/Weatherstation Apr 04 '20

It gives you the definition before exiting.

34

u/Skaviciusz Apr 04 '20

:q! - The best option

9

u/Galactic_Dev Apr 04 '20

Vim user spotted

3

u/[deleted] Apr 05 '20

Yet, the ! is superfluous in this case, since the tool is not able to overwrite anything.

26

u/[deleted] Apr 04 '20

ctrl+c

4

u/cbarrick Apr 05 '20

Ctrl+d

i.e. end-of-file

2

u/Kangalioo Apr 05 '20

That'll make it compatible with Unix shell scripting via pipes, too

6

u/Mcmofi Apr 04 '20

Well instead of a definition you obviously get a demonstration

5

u/martinjm97 Apr 04 '20

Use a Spanish word!

6

u/[deleted] Apr 04 '20

Quesadilla

7

u/ThreeJumpingKittens Apr 04 '20

Donde esta mis pantalones?

1

u/equecevi Apr 04 '20

Están aquí cariño, vuelve a la cama

31

u/eloydrummerboy Apr 04 '20

Additional ideas:

Have it clear the screen between each new word entry instead of scrolling down.

Have it write all definitions to a file, the same file everytime you run it, append only. Then you can review this regularly to help with your vocabulary. Or instead of append only, see if you can get it to always save new entries in alphabetical order.

Try to save this on going dictionary in a format that python can read into a dict. Look into pickle, or other serialization methods.

Write a program that reads the file with ask the definitions and allow you to press a key to scroll through them one set a time for review. Have options to do this in alphabetical order or random order. Have options that show only the word first so you can try to remember the definition, and then the definition on the next key press.

Add coloring to the console text.

8

u/Weatherstation Apr 04 '20

I'd also suggest turning it into a service with a REST API. That way you could extend it to all sorts of uses. You could have a command line client like your example, you could easily integrate it into slack with webhooks, or you could even have alexa make calls to it.

If anything it's a good exercise in writing services and working with APIs. Plus, an always running service could keep stats for what was looked up, keep a history of requests, and could even cache recent words, etc.

Anyway, good work.

13

u/Decency Apr 04 '20

No need for programming changes. Just set a bash alias:

alias define='python smartsnek'

Then just define blah will do what you'd like.

1

u/TheSchlooper Apr 04 '20

Or compile it via pip setup

1

u/Decency Apr 04 '20

I don't know what you mean but it sounds more complicated than a bash alias?

1

u/TheSchlooper Apr 04 '20

Maybe, but its something fun to learn

1

u/FruityWelsh Apr 05 '20

Does that package python with the program for use on machines without python (or the needed version)?

Also got any good links to tutorials on that?

2

u/TheSchlooper Apr 05 '20

There are ways to do that, that's more on the verge of compiling a stand-alone version of it in it's own container. I've barely tinkered with that, useful, but only really useful in certain scenarios.

The method I was talking about is a bit simpler that's using a setup.py configuration for a python-pip install. Honestly I don't know what it's called, I've just seen it in other projects and have copied/used the same technique in my own apps that I actively use for work, hah. It does may deployment really easy especially when you're using different libraries.

1

u/vEnoM_420 Apr 04 '20

Yes, that'd be great. It would be more awesome if OP makes this using a simple tkinter GUI in the future.

1

u/JS_int_type Apr 05 '20

Invoke the program via a bash function:

smartsnek() {
    python3 $HOME/bin/dictionary program $@
}

Dump that into your .bash_profile and then invoke using smartsnek $WORD.

1

u/CeeMX Apr 05 '20

Add a shebang to the python file and make it executable. That way you can call it with ./lookup word.

Add the dir into PATH and you can do it from everywhere. Much better than a program you have to start first. I for myself need to look up a word only every once in a while, so a loop would be contra productive.

1

u/eloydrummerboy Apr 05 '20

True, but OP's stated use case was while watching movies and podcasts. So the loop would not be constantly be running in the background outside of this set time, and I don't feel starting the program before the movie/podcast and ending after is too much work. Besides. they were already running the program for every word.

Both are good solutions and improve on the current design. I'll leave it to OP to decide which fits his needs best.

But, yes, as an 'always there' dictionary terminal application, your method would work best.

0

u/[deleted] Apr 04 '20

[deleted]

3

u/OneUselessUsername Apr 04 '20

Isn't the continue redundant?

4

u/theneonkoala Apr 04 '20

Looks awesome! Btw how did you make the terminal look like that?

6

u/[deleted] Apr 04 '20

Thanks, it's the default terminal that comes with Manjaro i3 edition

5

u/theneonkoala Apr 04 '20

I didnt know such a distro existed that looks amazing

1

u/ignorae Apr 04 '20

I was just about to ask the same thing. Looks gorgeous

1

u/el_programmador Apr 05 '20

You can bet your bottom dollar even Mark Shuttleworth can't distinguish it from an Ubuntu.

2

u/kindall Apr 04 '20

I realize this is /r/python, but why not just set up a browser keyword for this?

5

u/[deleted] Apr 04 '20

For me personally is that I like minimalistic things, including software - and the way I use my software. Try going on a website and you'll see that you are BOMBARDED with things that are not relevant to your current endeavor, but this way, you get just the information you asked for in the first place, nothing less nothing more.

2

u/Weatherstation Apr 04 '20

Once you're proficient at the command line, nothing seems as good.

Hell, I usually even just open python to do simple calculations instead of opening the calculator app.

1

u/Decency Apr 04 '20

Yeah you can do that with browser searches too. In Firefox it's called 'Add a Keyword for this Search', forget what it is in Chrome and they recently made it harder to use.

I'm in a browser much more than a terminal, but use cases differ!

11

u/[deleted] Apr 04 '20

Upvoted for the snek.

6

u/[deleted] Apr 04 '20

I did something similar. I just made a AHK script that got a word copied from the clipboard and looked it up on wiktionary.

5

u/elsantodom Apr 04 '20

You can set an alias for the program editing the .bashrc file in the home directory so you don't need to write all the text. I think that a while true will help you reduce the times you open the program and you can simply set a letter to use as a break

2

u/Weatherstation Apr 04 '20

Instead of creating an alias it would be better to just install or link the script into /usr/bin.

2

u/Barafu Apr 04 '20

Nice thing, but now just add this site as a search engine to your browser's search bar.

5

u/[deleted] Apr 04 '20

I'd rather not have to open up the browser at all

5

u/mauledbyakodiak Apr 04 '20

I frankly also really like this. If I can just open a terminal and then run a script without having to go to a website or yada yada yada, it's really nice.

3

u/isarl Apr 04 '20

Or use your phone to open up your favourite dictionary app or webpage in your mobile browser, and leave it open while you're listening/watching.

Having said that, there's a lot of value in reimplementing simple tools as learning exercises, so we shouldn't rain on OP's parade. For what it is, this tool seems well made.

2

u/[deleted] Apr 04 '20

Believe it or not, some of us know how to use smartphones and browsers yet prefer to run quick, light scripts in a terminal. iTerm has a cool shortcut (ctrl-space) that opens up a floating terminal that disappears when you click away or switch programs.

2

u/[deleted] Apr 04 '20

Also, there are people (I have ADD) who get easily distracted from any random notification, or will open other apps. When I'm working or learning I put my phone on DND and set it somewhere I can't see.

8

u/aufstand Apr 04 '20

Nice project. A sidenote for folks who want this with offline-capability: I recommend dictd + client and a few additional dictionaries. Usually available in your default Linux distribution. Especially the Jargon File, Devils Dictionary and things like foldoc, wordnet and several language translation dictionaries are part of my default install. Much better than my clunky Oxford Advanced Learners and it has Portuguese as well!

1

u/el_programmador Apr 05 '20

On Ubuntu, this is one of the things I do on a clean install:

sudo apt install dict dictd dict-gcide dict-wn

1

u/lucpet Apr 05 '20

So are you searching real English or the incorrect rubbish Americans think is English lol

1

u/[deleted] Apr 05 '20

I'm not really discriminating against words, what's the point of your comment?

1

u/prittiao Apr 06 '20 edited Apr 06 '20

Why do you separe the project in all that files instead of doing it all in one ?? Im new in python btw

2

u/[deleted] Apr 06 '20

No reason other than to keep stuff organized

3

u/robifis Apr 04 '20

That’s a fantastic idea!! Maybe even add it to a text file for future reference?

3

u/hughmern Apr 04 '20

I'm a native English speaker and when watching podcasts/movies very often I also find myself googling the definition of a word

2

u/mrkaragoz Apr 04 '20

Please make a smaller video next time. This one can’t hurt enough my eyes.

2

u/TankorSmash Apr 04 '20

Could save yourself some typing and hit Up Arrow, Ctrl W then type the next word. If it's a different session, use Ctrl R snek Ctrl W.

Alternatively make this an alias like alias snek=python smartsnek, and use it like snek levity.

2

u/SweetSoursop Apr 04 '20

So, a dictionary?

Put some simple web UI on it, and publish it. You'll get tons of traffic

2

u/anorexia_is_PHAT Apr 05 '20

Is it really simpler?

1

u/[deleted] Apr 04 '20

This is cool, you could add an alias to your terminal so you don't have to type all the python... stuff each time

2

u/Weatherstation Apr 04 '20

Putting it in /usr/bin is the better solution because that way it works for all users, not just the one who set up the .bashrc.

1

u/jungle_is_massive Apr 04 '20

Nice idea. If you make the script executable then you won't have to type python anymore 👍

1

u/retsotrembla Apr 04 '20

If you are running this on a Mac, consider using the Mac's built-in OCR library, and its built-in dictionary lookup so that you could just click with the mouse, it would grab the pixels under the mouse, find the word, OCR the word, and display the standard "lookup" popup.

1

u/tejonaco Apr 04 '20

I did something similar, one trick, put #!/usr/bin/python3 on the top and avoid write python everytime

2

u/isarl Apr 04 '20

Please don't do this. See my reply to OP elsewhere in this thread for why not to write #!/usr/bin/python3. It's fine to use a shebang, just use the right one.

2

u/tejonaco Apr 05 '20

Oh, you are right, but my distro is a little bit outdated and for any reason it calls python2 by default, that bother me more than once importing modules, but I understand that's not the rule, thanks anyway

2

u/isarl Apr 05 '20

Yeah, so in your case if you wanted to call python3 that you had installed then you would go #!/usr/bin/env python3 and if you wanted to use 2 specifically you could use #!/usr/bin/env python2 (or just #!/usr/bin/env python if there's no python2 on the PATH).

2

u/tejonaco Apr 05 '20

Interesting I will thanks

1

u/TofiMok Apr 04 '20

I've made something like this for learning french as well! Consider adding this program to your system path, so that you don't have to be in the application directory to use it. This way you can search words fast!

1

u/codeinsleep Apr 04 '20

Speech to text -> Neural Net for word complexity and commonality (either in hard texts or easy texts, solve for bool) -> highlight words with high complexity with manual input option -> output link to meaning -> if clicked echo definition

1

u/MohammadAminAli Apr 05 '20

Don't want to release it? seems useful!

1

u/MRshouldnotbehere Apr 05 '20

Nice project! Interesting to see different approaches to the same problem :) I've done something similar with their sibling site, thesaurus.com, to look up synonyms for words; https://github.com/andreaslarsson/lookup_console.

1

u/[deleted] Apr 04 '20

[removed] — view removed comment

2

u/kyle1elyk Apr 04 '20

Exactly what I was thinking

  alias smartsnek='python /path/smartsnek'  

Or similar