Today, I will share my experience in learning python text mining. If you browse in internet you will find a lot of regular expression tutorial, but I think it will make you confuse at first ✌️. So,to make it a simpler tutorial I will use an example.
So, I have a task to extract port data from a free text like this (file name getport.txt) :
show port description | match BA
2/1/7 AKSES_#2/1/7_1G_KAN.2#0/3
2/1/12 AKSES_#2/1/12_1G_KAN.1#0/
2/1/18 AKSES_#2/1/18_1G_KAN.1#0/
2/1/21 AKSES_#2/1/21_1G_KAN.2#0/
A:#
The objective of the program is to get port data in each row.
As we can see in above image, we have a yellow square that is very similar to red square, an output that we want to get. But we can distinguish it because in red square the text have space at the end of it. So, basically our output data have pattern format like this
decimalnumber/decimalnumber/decimalnumber (space)
OK, lets write the python code (v2.7)!!
import re
f = open(“getport.txt”, “r”)
f =f.read()
print f
port = re.findall(r’\d{1,2}[/]\d[/]{1,2}\d{1,2}\s’, f)
port = [w.strip() for w in port]
print port
The important part of this code is in bold. First, we need to import regular expression (re) module library with “import re”. Then we open and read our file “getport.txt” and safe it in a variable we call “f”. Then we search with findall function in “f” text. What we find? we find in “f” text that have an pattern format like above. So the regular expression used is like this.
\d{1,2} → this mean that we search decimal number with 1 or 2 digit, because our data have one or two digit
[/] → this mean that after decimal number our pattern is ‘/’ char
\s → this mean that the last character is matches any whitespace character, this is equivalent to the set
[ \t\n\r\f\v]
For a note, the output of findall function is an array.
Get Syaiful Andy’s stories in your inbox
Join Medium for free to get updates from this writer.
At last I use “w.strip() for w in port” because I want to delete all space character after port number. So I use strip() function in python to every array member in port variable.
That’s all for today, so simple right??
Thanks 😉







