Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Friday, 12 April 2019

OCR Python Assignment Tasks

Task 1 : Compressing text

Develop a program that analyses a sentence that contains several words without punctuation. When a word in that sentence is input, the program identifies all of the positions where the word occurs in the sentence. The system should not be case sensitive: Ask, ask, ASK should be treated as the same word.

For example, in the sentence

"ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"

The word ‘COUNTRY’ occurs in the 5th and 17th positions.

Analyze the requirements for this system and design, develop, test and evaluate a program to locate and return the position(s) of the word you have selected in a particular sentence or return an error message if the word is not in the sentence.

Task01 Description:


Please contact me at

immukesh72@gmail.com

for further assistance on such kind of assignments


Task 2 : Identifying Indivisual words in a sentence

Develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list.
For example, the sentence

"ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
contains the words ASK, NOT, WHAT, YOUR, COUNTRY, CAN, DO, FOR, YOU
The sentence can be recreated from the positions of these words in this list using the sequence
1,2,3,4,5,6,7,8,9,1,3,9,6,7,8,4,5

Save the list of words and the positions of these words in the sentence as separate files or as a single file.
Analyse the requirements for this system and design, develop, test and evaluate a program to:
• identify the individual words in a sentence and store them in a list
• create a list of positions for words in that list
• save these lists as a single file or as separate files.


Please contact me at immukesh72@gmail.com  for further assistance on such kind of assignments.


Task 3 : Compress The Text File With Several Sentences

Develop a program that builds upon the technique from Task 2 to compress a text file with several sentences, including punctuation. The program should be able to compress a file into a list of words and list of positions to recreate the original file. It should also be able to take a compressed file and recreate the full text, including punctuation and capitalisation, of the original file.

Analyse the requirements for this system and design, develop, test and evaluate a program to compress a text file and reproduce the original text from a compressed file. You will need to create a text file with more than one sentence to test your system.

Requirements: Develop a program that builds upon the technique from Task 2 to compress a text file with several sentences, including punctuation. The program should be able to compress a file into a list of words and list of positions to recreate the original file. It should also be able to take a compressed file and recreate the full text, including punctuation and capitalization, of the original file.

Steps to develop above program:


Please contact me at

immukesh72@gmail.com

for further assistance on such kind of assignments

Saturday, 3 December 2016

Python Mysql Database Access

There is a python module called MySQLdb through which we can access many databases like Mysql,Oracle,PostgreSQl,Sybase,GadFly etc.
Here i am going with Mysql on Linux operating system.
Other than MySQLdb module there is one more module called mysql-connector which also provide database access from python script.

Diffrence between MySQLdb and mysql-connector.
MySQLdb : MySQLdb is a C module that links against the MySQL protocol implementation in the libmysqlclient library. It is faster, but requires the library in order to work.

mysql-connector : mysql-connector is a Python module that reimplements the MySQL protocol in Python. It is slower, but does not require the C library and so is more portable.

MySQLdb:
MySQLdb is an interface or python module for connecting to a MySQL database server from Python.

Verify if MySQLdb  have installed in your machine. Try to run the following script.
    #!/usr/bin/python

    import MySQLdb


if it is throwing following error that mean MySQLdb module need to install in your machine.
    Traceback (most recent call last):
      File "test.py", line 3, in <module>
        import MySQLdb
    ImportError: No module named MySQLdb


To install MySQLdb module in your Unix/Linux OS, download zip file from MySQLdb Download page(http://pkgs.fedoraproject.org/repo/pkgs/MySQL-python/MySQL-python-1.2.2.tar.gz/532268f02870bea18c1d465e88afff30/MySQL-python-1.2.2.tar.gz) and run the following command.

You can also try wget command to download zip frile in your unix machine.

    $ wget http://pkgs.fedoraproject.org/repo/pkgs/MySQL-python/MySQL-python-1.2.2.tar.gz/532268f02870bea18c1d465e88afff30/MySQL-python-1.2.2.tar.gz
    $ gunzip MySQL-python-1.2.2.tar.gz
    $ tar -xvf MySQL-python-1.2.2.tar
    $ cd MySQL-python-1.2.2
    $ python setup.py build
    $ python setup.py install



Before starting create a test databases called mydb and table as customer with following table structure and values.
    mysql> select * from mydb.customer;

    +------------+--------------+----------------------+-----------+
    | customerid | customername | emailid              | accountno |
    +------------+--------------+----------------------+-----------+
    | 1001       | Neeraj singh | neeraj@gmail.com     |     30004 |
    | 1002       | Tanu         | tanu@gmail.com       |     30005 |
    | 1003       | Shivam Kumar | shivam@yahoo.com     |     30006 |
    | 1004       | vinay        | vinay.s@gmail.com    |     30007 |
    | 1005       | Ajay singh   | ajay.singh@gmail.com |     30008 |
    +------------+--------------+----------------------+-----------+


Example 01 : Read/Select operation

In read operation we need to use the following useful method to fetch or read the information from database.
fetchone() : It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.
fetchall(): It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves the remaining rows from the result set.
rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method.

#!/usr/bin/python

import MySQLdb

# Open database connection
conn = MySQLdb.connect("localhost","mukesh","mks123","mydb" )


# prepare a cursor object using cursor() method
cursor = conn.cursor()


# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM customer \
       WHERE customerid > '%d'" % (1003)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   print "Total count :"+str(cursor.rowcount)
   results = cursor.fetchall()
   for row in results:
      customerid = row[0]
      customername = row[1]
      emailid = row[2]
      accountno = row[3]
      # Now print fetched result
      print "customerid=%s,customername=%s,emailid=%s,accountno=%d" % \
             (customerid, customername, emailid, accountno )
except :
   print "Error: unable to fecth data"


# Close the cursor and disconnect from server
finally:
        cursor.close()
        conn.close()

Read operation with fetchone() method
#!/usr/bin/python

import MySQLdb


# Open database connection
conn = MySQLdb.connect("localhost","mukesh","mks123","mydb" )


# prepare a cursor object using cursor() method
cursor = conn.cursor()


# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")


# Fetch a single row using fetchone() method.
data = cursor.fetchone()


print "Database version : %s " % data


# Close the cursor and disconnect from server
finally:
        cursor.close()
        conn.close()

        

Ouptput:
Database version : 5.5.49-0ubuntu0.12.04.1

Example 02 : Insert Operation
#!/usr/bin/python


import MySQLdb


# Open database connection
conn = MySQLdb.connect("localhost","mukesh","mks123","mydb" )


# prepare a cursor object using cursor() method
cursor = conn.cursor()


# Prepare SQL query to INSERT a record into the database.
#sql = """INSERT INTO customer(customerid,
#         customername, emailid, accountno)
 #        VALUES ('1006', 'Mohan', 'mohan@reddif.com', '30009')"""


# Prepare dynamic SQL query to INSERT a record into the database.
sql = "INSERT INTO customer(customerid,\
         customername, emailid, accountno) \
                 VALUES('%s','%s','%s','%d')" \
         %('1006', 'Mohan', 'mohan@reddif.com', 30009)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   conn.commit()
except:
   # Rollback in case there is any error
   conn.rollback()


# Close cursor and disconnect from server
conn.close()
cursor.close()


Example 03 : Update Operation
Following procedure will update all records which having customername 'Mohan'.
#!/usr/bin/python


import MySQLdb


# Open database connection
conn = MySQLdb.connect("localhost","mukesh","mks123","mydb" )


# prepare a cursor object using cursor() method
cursor = conn.cursor()


# Prepare SQL query to UPDATE required records
sql = "UPDATE customer SET emailid = 'mohan.kumar@reddif.com'\

                          WHERE customername = '%s'" % ('Mohan')
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   conn.commit()
except:
   # Rollback in case there is any error
   conn.rollback()


# disconnect from server
conn.close()


Example 04 : Delete Operation
#!/usr/bin/python


import MySQLdb


# Open database connection
conn = MySQLdb.connect("localhost","mukesh","mks123","mydb" )


# prepare a cursor object using cursor() method
cursor = conn.cursor()


# Prepare SQL query to DELETE required records
sql = "DELETE FROM customer WHERE customerid = '%s'" % ('1006')
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   conn.commit()
except:
   # Rollback in case there is any error
   conn.rollback()


# disconnect from server
conn.close()


After performing this delete operation through python script. Connect mysql db and verify the operation successfully proceeded or not.



************************END*******************************


Monday, 23 May 2016

Python Script to write a xlsx file

we have a python module called XlsxWriter to write multiple worksheet in MS Excel 2007+ xlsx file. This module can be used to write text, numbers, formulas, hyperlinks and charts.
It supports features such as formatting and many more, including:
  •     100% compatible Excel XLSX files.
  •     Full formatting.
  •     Merged cells.
  •     Defined names.
  •     Charts.
  •     Autofilters.
  •     Data validation and drop down lists.
  •     Conditional formatting.
  •     Worksheet PNG/JPEG images.
  •     Rich multi-format strings.
  •     Cell comments.
  •     Integration with Pandas.
  •     Textboxes.
  •     Memory optimization mode for writing large files.

It supports Python 2.5, 2.6, 2.7, 3.1, 3.2, 3.3, 3.4, 3.5, Jython and PyPy and uses standard libraries only.

Installing XlsxWriter:
Using PIP :
$ sudo pip install XlsxWriter

Using Easy_install:
$ sudo easy_install XlsxWriter

Installing from a tarball:

Download the tarball of latest version and keep it into your working directory and run the following commands to install XlsxWriter module. I have downloaded XlsxWriter-0.8.7.tar.gz

$ tar -zxvf XlsxWriter-0.8.7.tar.gz
$ cd XlsxWriter-0.8.7
$ sudo python setup.py install

# Running a sample program

#!/usr/bin/python
import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Hello world')

workbook.close()




import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

# Insert an image.
worksheet.insert_image('B5', 'logo.png')

workbook.close()

Tuesday, 10 May 2016

Python Script to read and write a csv file

CSV stands for "comma separated values" is the most common import and export format for spreadsheets and databases. Python provides the csv module in which reader objects allow you to read the csv file and writer object to write a csv file. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.

Note : Python2.7 csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe.

Python Script to write testFile.csv :

Writing csv file is easy first you need to import csv module in your program and then csv.writer() will create a writer object and then csv.writer() object will create the empty csv file as per given arguments and later you can use writerow() to write the comma separated values.Look at the following program.

import csv

# Creating a file object in appending mode
f=open('myFile.csv','ab')try:
    # Creating the writer object and myFile.csv
    csvWriter = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
 
    # Writing the csv header
    csvWriter.writerow(['SNO','Employee','Salary'])
    
    # Writing the content into csv file
    csvWriter.writerow([1,"Jon Baker","20,000"])
    csvWriter.writerow([2,"Abhishek","60,000"])
    csvWriter.writerow([3,"Dinesh Kumar","28,000"])
    csvWriter.writerow([4,"Anita","22,000"])
    csvWriter.writerow([5,"Ajay Singh","26,000"])
finally:
    f.close()


Run the above program and confirm the myFile.csv has been generated with its contents.

Quoting:

There are four different quoting options, defined as constants in the csv module.

QUOTE_ALL
Quote everything, regardless of type.
QUOTE_MINIMAL
Quote fields with special characters (anything that would confuse a parser configured with the same dialect and options). This is the default
QUOTE_NONNUMERIC
Quote all fields that are not integers or floats. When used with the reader, input fields that are not quoted are converted to floats.
QUOTE_NONE
Do not quote anything on output. When used with the reader, quote characters are included in the field values (normally, they are treated as delimiters and stripped).

Python Script to read testFile.csv :

For reading the csv file, first create the file object of file for which you want to read in read mode. Use reader() to create an object for reading data from a CSV file. The reader can be used as an iterator to process the rows of the file in order. Look at below program:

import csv

# Creating a file object in appending mode
f=open('myFile.csv','rb')

try:
    csvReader=csv.reader(f)
    for row in csvReader:
        print row
finally:
    f.close()
   
The output you will get something like this.
['SNO', 'Employee', 'Salary']
['1', 'Jon Baker', '20,000']
['2', 'Abhishek', '60,000']
['3', 'Dinesh Kumar', '28,000']
['4', 'Anita', '22,000']
['5', 'Ajay Singh', '26,000']


If you want to read a particular column then provide the index while iterating the csvReader list. Look at the below example in which i am reading just second column of CSV file.

import csv

# Creating a file object in read mode
f=open('myFile.csv','rb')

try:
    csvReader=csv.reader(f)
    for row in csvReader:
        print row[1]
finally:
    f.close()
   
The output will be something like a below:

Employee
Jon Baker
Abhishek
Dinesh Kumar
Anita
Ajay Singh


Note : Open method have 2 argument open(filename,mode) , We have different following kind of modes:
r    : When the file will only be read
w  : When the file only writing (an existing file with the same name will be erased)
a   : Opens the file for appending; any data written to the file is automatically added to the end
r+ : Opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files

                  

                                ***************************************

Thursday, 28 April 2016

Python Script to read and write text files

Python Script to write myFile.txt:

The best option to writing text file is using "with" keyword. First we will create the file object f and then f.write('string_content\n') will create text file and write the content into text file.

with open('myFile.txt', 'a') as f:
    f.write("This is the test string01\n")

The above piece of code will create a myFile.txt file in the current directory means in the same location where we are keeping the script. You can give any path for the output file.

with open('D:\myFile.txt', 'a') as f:
    f.write("This is the test string01\n")



Once we create file object we can write many strings into the file.

 with open('D:\myFile.txt', 'a') as f:
    f.write("This is the test string01\n")
    f.write("This is the test string02\n")
    f.write("This is the test string02\n")



Python Script to read myFile.txt:

Use open() and create a file object "f" and the f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string.

f=open('myFile.txt', 'r')
f.readline()
   'This is the test string01\n'
f.readline()
   'This is the test string02\n'
f.readline()
   'This is the test string02\n'
f.readline()
   ''
f.readlines() will print all lines of the file as a list.
f=open('myFile.txt', 'r') 
f.readlines()     
 ['This is the test string01\n', 'This is the test string02\n', 'This is the test string02\n']


So finally the best way to read the file line by line is first take all lines into list using f.readlines() and then iterate the list.
f=open('myFile.txt', 'r') 
fList=f.readlines() 
for line in fList:     
 print line 
This is the test string01 
This is the test string02 
This is the test string02 
 

Note : Open method have 2 argument open(filename,mode) , We have different following kind of modes:
  • r    : When the file will only be read
  • w  : When the file only writing (an existing file with the same name will be erased)
  • a   : Opens the file for appending; any data written to the file is automatically added to the end
  • r+ : Opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.
  • On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files 

                                *********************************

Monday, 29 February 2016

Python Project : Media Downloader

Project Description :

The script has to parse a configuration file called feeds.txt that contains four column. The fourth column contains the URL of a xml file. The script should download this xml file and parse this xml and find all media file like .png,.jpg or .pdf file. The links of the media files are relative to the xmlfile.

Following is the sample feeds.txt file :

landau feed1 landaumedia http://www.ps.landaumedia.de/4cf36ec2503400027400014a/Medienlandschaft/xmlfeed.xml
landau feed2 landaumedia http://www.ps.landaumedia.de/4c8df1fe8feeb50d54000091/W%C3%B6chentlicher%20Pressespiegel/xmlfeed.xml
bahlsen  feed1 landaumedia http://www.ps.landaumedia.de/557e5bb721d6bc0e4c6572cc/T%C3%A4glicher%20Pressespiegel/xmlfeed.xml
block-house feed1 landaumedia http://www.ps.landaumedia.de/5065af429295461238cd388d/T%C3%A4glicher%20Pressespiegel/xmlfeed.xml
claas  feed1 landaumedia http://www.ps.landaumedia.de/55f9603c70e1df143858a56b/T%C3%A4glicher%20Pressespiegel/xmlfeed.xml
claas  feed2 meltwater https://app.meltwater.com/gyda/outputs/566fcddff1e0c684a2930228/rendering?apiKey=55944bdf484b6d23a61cd26e&type=xml

The script should read above file with four columns. The first column contains the name of the client. The second column contains the name of the feed, the third column contains the format name of the feed so that you can distinguish between the two type of feeds. The forth and last column contains the actual feed URL.

The script has to create following directory structure automatically for the above feeds.txt file.
├───bahlsen
│   └───feed1
│       └───landaumedia
│           └───2016-02-19
│               ├───article_1
│               ├───article_3
│               ├───article_4
│               ├───article_5
│               ├───article_6
│               ├───article_7
│               ├───article_8
│               └───article_9
├───block-house
│   └───feed1
│       └───landaumedia
│           └───2016-02-19
│               ├───article_1
│               ├───article_2
│               └───article_3
├───claas
│   ├───feed1
│   │   └───landaumedia
│   │       └───2016-02-19
│   │           ├───article_1
│   │           ├───article_2
│   │           ├───article_3
│   │           ├───article_4
│   └───feed2
│       └───meltwater
│           └───2016-02-19
└───landau
    ├───feed1
    │   └───landaumedia
    │       └───2016-02-19
    │           ├───article_1
    │           ├───article_2
    └───feed2
        └───landaumedia
            └───2016-02-19
                ├───article_1
                ├───article_2
                ├───article_3
                ├───article_4
                └───article_5

Note : article_* are the final directories where all media file like .pdf, .jpg, .png etc will store and it will look like below format.

./feeds/client1/feed1/2016-02-15/xmlfeed.xml
./feeds/client1/feed1/2016-02-15/article_1/die welt.png
./feeds/client1/feed1/2016-02-15/article_1/Welt_online_Die_Handelsblatt_plant_Klage_gegen_die_Lufthansa_1.pdf
./feeds/client1/feed1/2016-02-15/article_2/zzz_handelsblatt_com_530.png
./feeds/client1/feed1/2016-02-15/article_2/Handelsblatt_Online_Medienhaus_blaest_Wechsel_der_Rechtsform_ab_2.pdf
./feeds/client1/feed1/2016-02-15/article_3/frankfurter allgemeine zeitung online.png
Python Program for above problem


#!/usr/bin/python
# coding: UTF-8

#__author__ = 'Mukesh.Kumar' 

import os,time,subprocess
from xml.dom import minidom
import urllib,urlparse

def mediaExtractor(xmlUrl,directory):
# mediaListCommand="wget -q -O- "+xmlUrl+" | grep -iPo 'article_.*\.[a-z]{2,4}'"
 xmlFile=directory+"//xmlfeed.xml"
 mediaListCommand="cat "+xmlFile+" | grep -iPo 'article_.*\.[a-z]{2,4}'"
 mediaList=((subprocess.Popen(['/bin/bash', '-c', mediaListCommand], stdout=subprocess.PIPE)).communicate()[0]).splitlines()
 for med in mediaList:
  med1=med.split('/')
  artDir=med1[0]
  finalDir=directory+"//"+artDir
  
  if not os.path.exists(finalDir) and "/" in med:
   os.makedirs(finalDir)
  else:
   pass

  medURL=urlparse.urljoin(xmlUrl,med)
  print artDir
  print medURL
  try:
    urllib.urlretrieve(medURL,finalDir+"//"+med1[1])
  except:
   pass  
 

def feedProcessing(feedList):
        for feed in feedList:
   print "Processing feed : "+feed
   print "-----------------------------"
                feedSplit=feed.split(" ")
                dir1=feedSplit[0]
                dir2=feedSplit[1]
                dir3=feedSplit[2]
                dir4=time.strftime("%Y-%m-%d")
                xmlUrl=feedSplit[3]
                directory=os.getcwd()+"//"+dir1+"//"+dir2+"//"+dir3+"//"+dir4
#               print directory
                if not os.path.exists(directory):
                        os.makedirs(directory)
                else:
                        pass

    # Downloading xml file
    print "------Downloading xml file feed -------------------"
    try:
     urllib.urlretrieve(xmlUrl,directory+"//xmlfeed.xml")
    except:
     print "Some error while downloading xml file"

    try:
     mediaExtractor(xmlUrl,directory)
    except:
     print "Fail to extract media for : "+xmlUrl


def main():
        feedFilepath=os.getcwd()+"//feeds.txt"
        if os.path.exists(feedFilepath) == False:
                print "Feed file not found in current directory"
        else:
                print "Feed file found and processing : "+feedFilepath

                feedList=[]
                feedFile=open(feedFilepath,'r')
                feedLines=feedFile.readlines()
                for line in feedLines:
                        line=line.replace('\t',' ')
                        line=line.replace('\n','')
                        while "  " in line:
                                line=line.replace('  ',' ')

                        feedList.append(line)
                        print line
      print "------------------"
                feedProcessing(feedList)


# main()
if __name__ == "__main__":
    main()

Related Posts Plugin for WordPress, Blogger...