Today, I just felt like coding, so I did. No big plan, just a random idea that popped into my head. I figured, why not try building a super simple command-line tool to, uh, count words in a text file? Yeah, I know, not exactly groundbreaking, but hey, it’s all about the process, right?
First, I fired up my trusty text editor. I’m using Python for this because, well, it’s Python. It’s just easy to get things done quickly.
Started with the basics, you know, getting the filename from the user as input:
python
filename = input(“Enter the filename: “)
Then, opened up the file. Had to remember that whole `try…except` thing to handle potential errors, like if the file doesn’t exist. Classic stuff.
python
try:
with open(filename, ‘r’) as f:
contents = *()
except FileNotFoundError:
print(“Oops! File not found.”)
exit()
After that, the “hard” part: splitting the file contents into individual words. I just used the `split()` method. Works pretty well for basic text, I guess.
python
words = *()
Then, the easy part: counting, counting all of those words I got now.
python
word_count = len(words)
Finally, spit out the result to the user. Nothing fancy, just a simple print statement:
python
print(f”The file contains {word_count} words.”)
Ran the thing, and… it worked! First try! Okay, maybe not the first try. I definitely messed up the file handling bit at first. But it worked eventually.
The whole thing took, like, maybe 20 minutes? And most of that was just me fiddling with the code and making sure I didn’t mess up something obvious.
The result is pretty satisfying, although it’s just a little and simple pratical coding, I made it. Maybe I will try something more complex next time.