Thursday 15 May 2014

Word Count using Python 3

In two days' time I need to submit the oral presentation slides to the IDB Scholars Scientific Symposium organiser. I need to re-organise the data which I got from my Masters dissertation since I sorta made a mess with the data analysis back then. Looking at it almost a year later amazed me how oft I was! *chuckles* I guess I did progress slightly after being at Cambridge for four months. Today is the first day (maybe 2nd day) of my 5th month.

BTW, my MFSc. (Erasmus Mundus) project was of DNA profiling.

As I was arranging the edited data with all the missing alleles and I got to the point of... "Err... How many lines are there in this document?" I know I can always use MS-Word's wordcount function, but I am feeling kinda adventurous, I used Python 3 script which I've recently learned... And they worked fine. So anyone who want to do word count, the script is as below.

data = open ("filename")
# e.g. of "filename" is "C:/Users/KherXing/treasure.txt"

n_lines = 0
n_words = 0
n_chars = 0

for line in data:
    n_lines += 1
    line_words = line.split()
    n_words += len (line_words)
    n_chars += len (line)

data.close ()
print (n_lines, n_words, n_chars)

No comments:

Post a Comment

Positive suggestions help to keep me going. Thanks! :)