![]() Print("The number of words is ", num_words) This should give us the number of words, as in English, words are separated by space (as if you didn’t know already). ![]() We are splitting the file we read on spaces. Out: Ĭoming back to our example: words = data.split(" ") Here, I split on a comma: In : "The birds, they are flying away, he said.".split(",") Python returned a list with four elements. I took a sentence “I am a boy” and split it on a space. To see how this works, I’ll fire up an IPython console. The function returns a list (which is what Python calls arrays) of the string split on space. In the example above, we are splitting on a space. One is the split() function which splits the string on the given parameter. Python has several in built functions for strings. We’ll be using the file count_words.py in the WordCount folder. Okay, so we can read a file and print it on the screen. Go to the folder called WordCount, and run the file there: python. On Windows, you’ll need to do: python read_file.py You might have to make the file executable. data = f.read()Īfter opening the file, we read its contents into a variable called data, and close the file. You can also read/write binary files, however we won’t go into that for the moment. Other common modes are w for write, a for append. The r means the file will be opened in a read only mode. Later on, we will cover reading from the command line, but for now, the path is hard coded. It must exist in the current directory (ie, the directory you are running the code from). We simply open a file called “birds.txt”. It doesn’t do any harm on Windows (as anything that starts with a # is a comment in Python), so we keep it in. It also tells Linux which interpreter to use (Python in our case). It tells the shell that this is a Python file, and should be run as such. The first line that starts with a #! is used mainly on Linux systems. ![]() The file we are working with is read_file.py, which is in the folder Wordcount. This is more interesting than just printing Hello World to the screen. We are going to build a baby version of that. The wc utility is quite advanced, of course, since it has been around for a long time. To get the number of words, lines and characters in a file. Those of you who have used Linux will know this as the wc utility. We will build a simple utility called word counter. Okay folks, we are going to start gentle. This chapter is for those new to Python, but I recommend everyone go through it, just so that we are all on equal footing. Machine Learning with an Amazon like Recommendation Engine Introduction to Pandas with Practical Examples (New)Īudio and Digital Signal Processing (DSP)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |