Jan 2, 2013

Python Application 4 - Replace Text Content


Step 1

Open any text editor (gedit,pico,vi,nano) then enter the following python script and save the file with .py extension.

#!/usr/bin/python
#Author : Jijo K Jose
print "\n------------------------------------\nChapter 22 - Regular Expression 5 \n------------------------------------\n"
import re
in_str = raw_input("Enter a text         : ")
se_str = raw_input("Enter search string  : ")
re_str = raw_input("Enter replace string : ")
count = 10
reg1 = re.compile(se_str)
print "Result : ",reg1.sub(re_str,in_str,count)
print "\n-----------------------------------\n"
#END

Python Application 3 - Check Email Address

Step 1

Open any text editor (gedit,pico,vi,nano) then enter the following python script and save the file with .py extension.

#!/usr/bin/python
#Author : Jijo K Jose
print "\n------------------------------------\nChapter 20 - Regular Expression 4 \n------------------------------------\n"
import re
in_str = raw_input("Enter an email address : ")
se_str = "\w+@\w+\.[com|in|org|net]"
reg1 = re.compile(se_str)
search1 = reg1.search(in_str)

if search1:
 print "\nValid email address"
else:
 print "\nInvalid email address"

print "\n-----------------------------------\n"
#END

Python Application 2 - Extract File Content

Step 1

Open any text editor (gedit,pico,vi,nano) then enter the following python script and save the file with .py extension.

#!/usr/bin/python
#Author : Jijo K Jose
f1 = open("logfile","r")
for i in f1.readlines():
 j = i.split(' ')
 print j
#END

Python Application 1 - Format File Content

Step 1

Open any text editor (gedit,pico,vi,nano) then enter the following python script and save the file with .py extension.

#!/usr/bin/python
#Author : Jijo K Jose
input_file = raw_input("\nEnter input file name : ")
output_file = "file_new.txt"
h1 = open(input_file,"r")
print "\n----------------------------"
print "Input File Content"
print "----------------------------\n"
for i in h1:
 print i,

h1.close()
h1 = open(input_file,"r")
h2 = open(output_file,"w")
k=0
for i in h1:
 i2 = i.split(',')
 for j in i2:
  n = len(j)
  if j[n-1] =="\n":
   h2.write(j)
 else:
  h2.write(j)

  h2.write("\n")

h1.close()
h2.close()

print "\n---------------------------"
print "Output File Content - file_new.txt"
print"----------------------------\n"
h1 = open(output_file,"r")
for i in h1:
 print i,
print "\n---------------------------\n"
#END