Sunday 4 October 2020

Extract audio from video file

 Audio to Video Convertor:




import moviepy.editor
import tkinter.filedialog
print("press Y to choose the video file to enter:")
if input().casefold()=='y':
    video_path=tkinter.filedialog.askopenfilename()
    video=moviepy.editor.VideoFileClip(video_path)
    audio=video.audio
    audio.write_audiofile('Audio1.mp3')
else:
    print("You need to choose a file to move ahead") 
 

  Read more about moviepy: https://pypi.org/project/moviepy/

Read about tkinter: https://docs.python.org/3/library/tkinter.html

Tuesday 15 September 2020

Writing text to an Image

 


In this project we are going to learn how we can add text to an image.

This can be used

  •  to create an Image quote in Python.
  • to create watermark in Python

 

We will be using PIL (pillow) Library in this project

To create Image we will use Image and ImageDraw module

To set fonts we will use ImageFont module

and

To write text on an image we will use multiline_text() method if ImageDraw module 

 

To Create an Image quote we require a background Image of our own choice on which we can write our quote

Lets define the tasks to be be performed for this project and work accordingly

Task 0: Import libraries:

from PIL import Image, ImageDraw, ImageFont

Task 1: Read an Image

imgObject=Image.open('full or relative path of your image')

Image.open() reads the image and returns an Image object


Task 2: Set the font of the text you want to add to the image

font_object = ImageFont.truetype("E:\\Font\\sunday-spring\\Sunday Spring.ttf", 350)

Download any font file of your own choice from google and  specify the path inside truetype() method of ImageFont class

If you font file is with extension .otf then you can call opentype() method of ImageFont class

font_object = ImageFont.opentype("E:\\Font\\sunday-spring\\Sunday Spring.otf", 350)

Task 3 : Creating ImageDraw object to draw text on an Image

drawing_object = ImageDraw.Draw(imgObject)

Inside the ImageDraw.Draw we need to specify image object so that we can bind the drawing pen to the image

Task 4: Write the text 

drawing_object.multiline_text((400,800), "MV's Code Guide", font=font_object, fill=(0, 0, 0))

With the drawing object call multiline_text() method to add multiline text or else you can call text() method to add single line text

Inside multiline_text() method :

  • First parameter is xy coordinate of Top left corner of the text.
  • Second Parameter is- Text to be drawn.
  •  Third parameter is : font – An ImageFont instance 
  • Fourth parameter is : fill – Color to use for the text.
You an also specify other parameter like
  • spacing – The number of pixels between lines.
  • align"left", "center" or "right".
  • direction – Direction of the text. It can be "rtl" (right to left), "ltr" (left to right) or "ttb" (top to bottom). Requires libraqm.

 Task 5: Save the new Image with text:

drawing_object.save('new_image.jpg')

Full code:

#Example: Create Image Quote

from PIL import Image, ImageDraw, ImageFont

# create an image object
#imgObject = Image.new("RGB", (500, 500), (255, 255, 255))
 
imgObject=Image.open('Path of Image')
 
 
# get a font object
font_object = ImageFont.truetype("E:\\Font\\sunday-spring\\Sunday Spring.ttf", 350)
 
 
# get a drawing context
drawing_object = ImageDraw.Draw(imgObject)

 
# draw multiline text
drawing_object.multiline_text((400,800), "MV's Code Guide", font=font_object, fill=(0, 0, 0))
 
 
# save the image
drawing_object.save('new_image.jpg')

 

Sunday 13 September 2020

Extract Text From Image Using Python

 

 

We are going to use pytesseract and pillow library to work on this project!

Before you start coding, you need to complete three tasks:

1. Click on the link below and install tesseract-OCR

https://github.com/UB-Mannheim/tesseract/wiki

After you install the setup successfully, take a note of where you are saving the file because we need that path in our code.

2. Install pytesseract by using command : pip install pytesseract

3. Install pillow by using command : pip install pillow 

 

Source Code:

 
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
value=Image.open('logo.png')
text=pytesseract.image_to_string(value)
print("Extracted Data is: \n ", text) 
 

Notice that if you want to add full path, you need to add double slash (\\) instead of single slash (\) in you path

For Example: If your path looks like this: D:\Python_Program\my_Image.jpg

Then replace \ with \\

something like : D:\\Python_Program\\my_Image.jpg

Or

Add  alphabet 'r' before your string
example:     r'C:\Program Files\Tesseract-OCR\tesseract.exe'

and then you are good to go!

 

Thursday 10 September 2020

Spell Checker with Python

 We can use two different packages to create spell checker

1. Using textblob

2. Using pyspellchecker

Video Explanation:


 

 

 Source Code:

 Using textblob:

 
from textblob import TextBlob
misspelled_word= "Incorrct"
corrected_word= TextBlob(misspelled_word).correct()
print("Misspelled Word:",misspelled_word)
print("Corrected Word: ",corrected_word)

# you can also use list of misspelled words
print("========================================================")
misspelled_word_list=['Incorrct','Mang','Summay','Watr','Appl']
for word in misspelled_word_list:
    correct_word=TextBlob(word).correct()
    print("Misspelled Word:",misspelled_word_list)
    print("Corrected Word: ",correct_word) 
 

Using pyspellchecker:

 
from spellchecker import SpellChecker
spell=SpellChecker()
misspelled_word=spell.unknown(['Incorrct', 'Summry','Mondy','Spellng','Pyhon'])
print(type(misspelled_word))
for word in misspelled_word:
    print("Corrected word is ", spell.correction(word))
    print("Candidate words:",spell.candidates(word)) 
 
 


You can play around this code and make changes according to your need!

You can also read a text file and use this code to check the spellings in the file


from textblob import TextBlob
from spellchecker import SpellChecker

f=open('demo.txt','r')
data=str(f.read())
print(data)
# you can also use list of misspelled words
print("\n\n**************************Using textblob**************************************")
misspelled_word_list= data.split()
for word in misspelled_word_list:
    correct_word=TextBlob(word).correct()
    print("\nWord: ",word)
    print('------------------------------')
    print("Corrected Word: ",correct_word)
    print("\n================================")

print('\n***************************Using pyspellchecker***********************************')
spell=SpellChecker()
misspelled_word=spell.unknown(misspelled_word_list)
print(type(misspelled_word))
for word in misspelled_word:
    print("\nword: ",word)
    print('--------------------------------------------')
    print("Corrected word is ", spell.correction(word))
    print('--------------------------------------------')
    print("Candidate words:",spell.candidates(word))
    print("\n================================")

f.close()

  


output:

Artifcial intelligence (AI), someties called macine intelligence, is intellience demonstated by machines, unlike the
naural intelligence dislayed by humans and animls.



**************************Using textblob**************************************

Word:  Artifcial
------------------------------
Corrected Word:  Artificial

================================

Word:  intelligence
------------------------------
Corrected Word:  intelligence

================================

Word:  (AI),
------------------------------
Corrected Word:  (of),

================================

Word:  someties
------------------------------
Corrected Word:  sometimes

================================

Word:  called
------------------------------
Corrected Word:  called

================================

Word:  macine
------------------------------
Corrected Word:  machine

================================

Word:  intelligence,
------------------------------
Corrected Word:  intelligence,

================================

Word:  is
------------------------------
Corrected Word:  is

================================

Word:  intellience
------------------------------
Corrected Word:  intelligence

================================

Word:  demonstated
------------------------------
Corrected Word:  demonstrated

================================

Word:  by
------------------------------
Corrected Word:  by

================================

Word:  machines,
------------------------------
Corrected Word:  machines,

================================

Word:  unlike
------------------------------
Corrected Word:  unlike

================================

Word:  the
------------------------------
Corrected Word:  the

================================

Word:  naural
------------------------------
Corrected Word:  natural

================================

Word:  intelligence
------------------------------
Corrected Word:  intelligence

================================

Word:  dislayed
------------------------------
Corrected Word:  displayed

================================

Word:  by
------------------------------
Corrected Word:  by

================================

Word:  humans
------------------------------
Corrected Word:  humans

================================

Word:  and
------------------------------
Corrected Word:  and

================================

Word:  animls.
------------------------------
Corrected Word:  animals.

================================

***************************Using pyspellchecker***********************************
<class 'set'>

word:  (ai),
--------------------------------------------
Corrected word is  (ai),
--------------------------------------------
Candidate words: {'(ai),'}

================================

word:  someties
--------------------------------------------
Corrected word is  sometimes
--------------------------------------------
Candidate words: {'sometimes'}

================================

word:  machines,
--------------------------------------------
Corrected word is  machines
--------------------------------------------
Candidate words: {'machines'}

================================

word:  intelligence,
--------------------------------------------
Corrected word is  intelligence
--------------------------------------------
Candidate words: {'intelligences', 'intelligence'}

================================

word:  demonstated
--------------------------------------------
Corrected word is  demonstrated
--------------------------------------------
Candidate words: {'demonstrated'}

================================

word:  naural
--------------------------------------------
Corrected word is  natural
--------------------------------------------
Candidate words: {'natural', 'aural', 'neural'}

================================

word:  dislayed
--------------------------------------------
Corrected word is  displayed
--------------------------------------------
Candidate words: {'displayed', 'dismayed'}

================================

word:  animls.
--------------------------------------------
Corrected word is  animals
--------------------------------------------
Candidate words: {'animist', 'animus', 'animals', 'animism'}

================================

word:  macine
--------------------------------------------
Corrected word is  machine
--------------------------------------------
Candidate words: {'machine', 'maine', 'racine', 'maxine', 'marine'}

================================

word:  intellience
--------------------------------------------
Corrected word is  intelligence
--------------------------------------------
Candidate words: {'intelligence'}

================================

word:  artifcial
--------------------------------------------
Corrected word is  artificial
--------------------------------------------
Candidate words: {'artifical', 'artificial'}

================================

 


Saturday 22 August 2020

Counting vowels in a string

 Using count() method:

string_data=input("Enter a string:")
vowels={'a','e','i','o','u'}
# Using Count() Method
list1=[]
for ch in string_data:
	if ch in vowels:
		if ch not in list1:
			list1.append(ch)
			print("{} occurred {} times".format(ch,string_data.count(ch)))

Without using count() method:

string_data=input("Enter a string:")
vowels={'a','e','i','o','u'}
d={}
for ch in string_data:
	if ch in vowels:
		d[ch]=d.get(ch,0)+1

print(d)
for key,value in sorted(d.items()):
	print(key,"occurred",value,"times")

Friday 21 August 2020

Counting number of occurrences of each character in a string


Using count() method:

string_data=input("Enter string: ")
l=[]
for x in string_data:
	if x not in l:
		l.append(x)
		print(x,"occurred",string_data.count(x),"times")

Without using count() method:

string_data=input("Enter string: ")
d={}
for x in string_data:
	d[x]=d.get(x,0) + 1
print(d)
print(d.items())
# for meaningful output
for key,value in sorted(d.items()):
	print(key,"occurred",value,"times")  

 

Question by Subscriber: 

 How to ignore special characters like ? , . etc

If you want to ignore special characters and focus on the alphabets and digits only, then you can do that by some extra work

You  can either import string class to get a set of all characters that you need to focus on, or you can manually add the set of characters you particularly want to focus on.

we will name them as valid_characters
Here goes the code:

import string
string_data=input("Enter string: ")
l=[]
valid_characters=set(string.ascii_letters+string.digits)
for x in string_data:
	if x in valid_characters:
		if x not in l:
			l.append(x)
			print(x,"occurred",string_data.count(x),"times")

Output: 

or

string_data=input("Enter string: ")
l=[]
valid_characters=set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+'0123456789')
for x in string_data:
	if x in valid_characters:
		if x not in l:
			l.append(x)
			print(x,"occurred",string_data.count(x),"times")



Hope you like it ..!

Thursday 13 August 2020

Removing duplicate characters from the string


 

 Sample Input: sssssssssssssssddddeeeeggggggghhhhh

Output: sdegh

1st way:

string_data=input("Enter string: ")
result=''
for character in string_data:
	if character not in result:
		result=result+character
print("You entered: ",string_data)
print("Final result after removing duplicate characters: \n", result )

  

2nd way:

string_data=input("Enter string: ")
list_data=[]

for character in string_data:
	if character not in list_data:
		list_data.append(character)
result="".join(list_data)		
print("You entered: ",string_data)
print("Final result after removing duplicate characters: \n", result )

Python Program for specific requirement-2

Sample Input: d8s2b5r6

Output:            dlsubgrx

string_data=input("Enter string: ")
result=''
for character in string_data:
	if character.isalpha():
		result=result+character
		previous=character
	else:
		digit=int(character)
		new_character=chr(ord(previous)+digit)
		result=result+new_character

print("You entered: ",string_data)
print("Final result : \n", result )

Python Program for specific requirements

Requirement:
Sample Input: s4b6c5a2d9

Output: ssssbbbbbbcccccaaddddddddd

string_data=input("Enter string: ")
result=''
for character in string_data:
	if character.isalpha():
		alphabet=character
	else:
		digit=int(character)
		result=result+alphabet*digit
print("You entered: ",string_data)
print("Final result: \n", result )

Requirement:
Sample Input:
ssssbbbbbbcccccaaddddddddd

Output: 4s6b5c2a9d    

string_data=input("Enter string: ")
result=''
previous=string_data[0]
character_count=1
i=1
while i<len(string_data):
	if string_data[i]==previous:
		character_count=character_count+1
	else:
		result=result+str(character_count)+previous
		previous=string_data[i]
		character_count=1
	if i==len(string_data)-1:
		result=result+str(character_count)+previous
	i=i+1
print("You entered: ",string_data)
print("Final result: \n", result )

Sort characters in a string

 Assume input string contains only alphabet symbols and digits.

We need to write a program to sort characters of the string were we will sort alphabets first and then digits will follow

Sample Input: C8N9A2U6R5B7

Output: ABCNRU256789

string_data=input("Enter some alphanumeric string to sort: ")
alphabets=[]
digits=[]
for ch in string_data:
	if ch.isalpha():
		alphabets.append(ch)
	else:
		digits.append(ch)
result=''.join(sorted(alphabets)+sorted(digits))
print("You entered: ",string_data)

print("Final result after Sorting: \n", result )

Merge two strings

 Merge two strings by taking characters alternatively from each string

Sample string 1 :  PYTHON
Sample string 2 :  python
Output:  PpYyTtHhOoNn 

Let us understand the two scenarios of this problem

Scenario1:  If both the strings are of same length:

string1=input("Enter first string: ")
string2=input("Enter second string: ")
i,j=0,0 # object initialization using Tuple Unpacking
result=""
while i<len(string1) or j<len(string2):
	result=result+string1[i]+string2[j]
	i=i+1
	j=j+1
print("You entered first string : ",string1)
print("You entered second string : ",string2)
print("Final result after alternate merge: \n", result )

Scenario 2:  If the strings have different length:

string1=input("Enter first string: ")
string2=input("Enter second string: ")
i,j=0,0 # object initialization using Tuple Unpacking
result=""
while i<len(string1) or j<len(string2):
	if i<len(string1):
		result=result+string1[i]
		i=i+1
	if j<len(string2):
		result=result+string2[j]
		j=j+1
print("You entered first string: ",string1)
print("You entered second string: ",string2)
print("Final result after alternate merge: \n", result )

Print characters present at even and odd index separately

 1st Way :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
string_data=input("Enter a string: ")
print("Characters present at even index position: ")
i=0
while i<len(string_data):
	print(string_data[i])
	i=i+2
print("Characters present at odd index position: ")
i=1
while i<len(string_data):
	print(string_data[i])
	i=i+2

 2nd Way:

string_data=input("Enter a string: ")
print("Characters present at even index position: ")
print(string_data[::2]) # or
print(string_data[0::2])
print("Characters present at odd index position: ")
print(string_data[1::2])

Reverse internal content of every second word

 Sample Input: one two three four five six seven eight

Output: one owt three ruof five xis seven thgie

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
string_data=input("Enter a string: ")
list1=string_data.split()
print(list1)
list2=[]
i=0
while i<len(list1):
	if i%2==0:
		list2.append(list1[i])
	else:
		list2.append(list1[i][::-1])# Reversing word and then adding to list2
	i=i+1
print(list2)
result=" ".join(list2)
print("The string you entered:", string_data, sep="\n")
print("The result after reversing order of words in the string: ", result, sep="\n")

Reverse the internal content of each word

 

 

 

Sample Input: Hello Python

Output: olleH nohtyP

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
string_data=input("Enter a string: ")
list1=string_data.split()
print(list1)
list2=[]
for word in list1:
	list2.append(word[::-1]) # Reversing word and then adding to list2
print(list2)
result=" ".join(list2)
print("The string you entered:", string_data, sep="\n")
print("The result after reversing order of words in the string: ", result, sep="\n")

 

Reverse order of words in a string

 

 

Sample Input: Hello everyone ! Welcome to MV's Code Guide

Output: Guide Code MV's to Welcome ! everyone Hello

Using Slice operator:

1
2
3
4
5
6
7
8
string_data=input("Enter a string: ")
list1=string_data.split()
#Using Slice Operator to reverse the items of list1
list2=list1[::-1]
# Using join() to form a string from items of list2 
result=" ".join(list2)
print("The string you entered:", string_data, sep="\n")
print("The result after reversing order of words in the string: ", result, sep="\n")

 Using While loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
string_data=input("Enter a string: ")
list1=string_data.split()
print(list1)
list2=[]
i=len(list1)-1
while i>=0:
	list2.append(list1[i])
	i=i-1
print(list2)
result=" ".join(list2)
print("The string you entered:", string_data, sep="\n")
print("The result after reversing order of words in the string: ", result, sep="\n")

Wednesday 12 August 2020

String Reversal

 Python program to reverse a string:

 

There are three ways to reverse a string in Python:

1st way: Using Slice Operator: 

(To learn about slice operator click here)

1
2
3
4
 
string_data=input("Enter data you want to reverse")
result=string_data[::-1]
print("The string data you entered is :", string_data)
print("The reversed string is:", result)
 

  2nd way: Using reversed() function:

Python provides inbuilt function reversed()

It returns reversed object and you can use join() method of strings to get your required output form reversed object.

1
2
3
4
5
6
7
string_data=input("Enter data you want to reverse")
reversed_object=reversed(string_data)
print("The string data you entered is :", string_data)
for character in reversed_object:
	print(character,end='')
print()
print(type(reversed_object))

3rd way : Using While loop:

1
2
3
4
5
6
7
8
string_data=input("Enter data you want to reverse: ")
result=""
i=len(string_data)-1
while i>=0:
	result=result+string_data[i]
	i=i-1
print("The string data you entered is :", string_data)
print("String data after reversal: ", result)