0% found this document useful (0 votes)
8 views

Natural language processing-Section (1)

The document provides a comprehensive introduction to Python programming, covering its basics, installation, data types, variables, control structures, and file handling. It includes practical examples and tasks for readers to practice their skills. Additionally, it references external resources for further learning and troubleshooting.

Uploaded by

dw9324764
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Natural language processing-Section (1)

The document provides a comprehensive introduction to Python programming, covering its basics, installation, data types, variables, control structures, and file handling. It includes practical examples and tasks for readers to practice their skills. Additionally, it references external resources for further learning and troubleshooting.

Uploaded by

dw9324764
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Language Engineering

Prepared by: Abdelrahman M. Safwat

Section (1) – Python Basics


What is Python?

“Python is an interpreted, high-level,


general-purpose programming language.
Created by Guido van Rossum and first
released in 1991, Python's design philosophy
emphasizes code readability with its notable
use of significant whitespace. ”
2
Installing Python

We’ll be using the Anaconda Python distribution,


which can downloaded through this link:
https://www.anaconda.com/distribution/#downloa
d-section
Download the Graphical Installer of Python 3.7
according to your system (32-Bit or 64-Bit).
3
Installing Anaconda

4
Installing Anaconda

5
Installing Anaconda

6
Opening Anaconda

7
Opening Jupyter Notebook

8
Opening Jupyter Notebook

9
Having trouble with Anaconda or
Jupyter?

If you’re having trouble setting up or installing


Anaconda, you can use this instead:
https://colab.research.google.com/drive/1WM2ar_
4b7QMgfJ-qwgjJyU4CLIgUUgHw
Once it’s open, click on “Open in playground”.
10
Python Data Types

 In programming, data type is an important concept.


 Variables can store data of different types, and different types can do different things.
 Python has the following data types built-in by default, in these categories:

Text Type: str Set Types: set, frozenset


Numeric Types: int, float, complex Boolean Type: bool
Sequence Types: list, tuple, range Binary Types: bytes, bytearray, memoryview
Mapping Type: dict None Type: NoneType

11
Python Data Types

 Useing type() function to get the datatype.

x = 5
print(type(x))

Result : <class 'int'>

12
Variables

 Declaring variables in Python is easy. You don’t need to


specify the datatype, you just type the variable name and
assign a value to it.
this_is_an_integer = 1
this_is_a_float = 1.99
this_is_a_boolean = True
this_is_a_string = “Hello World”
this_is_a_list = [“Apples”, 3, True]
this_is_a_dictionary = {“name”: “Midoriya”, “age”: 16, “quirk”: “All for One” }

13
Printing a variable or a message

 Using the print() function, you can output a message, a


variable, or a combination to the console.

print(this_is_a_string)

Result : Hello World

14
Accessing items in lists or
dictionaries

 To access an item in a list, you specify the index between


square brackets. While to access an item in a dictionary, you
specify the name of the key of the value you want.
print(this_is_a_list[1])
print(this_is_a_dictionary[“name”])

Result :
3
Midoriya

15
Arithmetic Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation (power)
// Floor division

16
Arithmetic Operators

print(1 + 1)
print(1 – 1)
print(2 * 3)
print(6 / 2)
print(4 % 2)
print(5 // 2)

Result :
2
0
6
3
0
2 17
Conditionals

 If conditionals in Python are similar to other languages,


but instead of curly brackets, white space is used.
Also, else if statements are called elif.
if(this_is_a_boolean):
print(“This is true”)
if(this_is_an_integer < 0):
print(“Less than 0”)
elif(this_is_an_integer == 0):
print(“Equals 0”)
else:
print(“Greater than 0”)

Result :
This is true 18
Greater than 0
Logical Operators

Operator Equivalent to
and &&
or ||
not !

if ((this_is_an_integer == 1 and this_is_a_float == 1.99) or (not(this_is_a_boolean))):


print(“One of the conditions above is true.”)

19
Loops

 Python has two primitive loop commands:


• while loops
• for loops
 While while loops stays the same, for loops on the other
while(this_is_a_boolean):
hand are a bit different.
print(“This is an infinite loop”)

for i in range(10):
print(“This will loop 10 times”)

for x in this_is_a_list:
print(x)

for key, value in this_is_a_dictionary.items(): 20


print(“Key: ” + key + “ Value: ” + value)
While Loops

 With the while loop we can execute a set of statements


as long as a condition is true.

i = 1
while i < 6:
print(i)
i += 1

21
For Loops

 A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
 With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc.

fruits = for x in "banana":


["apple", "banana", "cherry"] print(x)
for x in fruits:
print(x)

22
Loops ( break and continue )

 With the break statement we can stop the loop


 With the continue statement we can stop the current iteration of the loop, and
continue with the next

fruits = i = 0
["apple", "banana", "cherry"] while i < 6:
for x in fruits: i += 1
print(x) if i == 3:
if x == "banana": continue
break print(i)

Result :apple Result :1


banana 2 23
4
Comments

 In Python, # is used for single line comments, while


three “
# This isare used
a single line for multi-line
comments comments
“””
This
is
a
multi-line
comment
“””

24
Example

list_of_favorites = [
{“name”: “Ahmed”, “likes”: ”watermelon”},
{“name”: “Michael”, “likes”: “apples”},
{“name”: “Sara”, “likes”: “grapes”}
{“name”: “Mariam”, “likes”: “mango”}
]

for person in list_of_favorites:


print(person["name"] + " likes " + person["likes"])

25
Try it out yourself

 Code:
https://colab.research.google.com/drive/1KmZ7HPJS_Mq
s3IshXf4wsjBZa5VeENat

26
Task #1

 Write a Python program that print all prime numbers


between 25 and 40

27
Task #2

 Write a Python program that check if all items in the


following list are int

list1=[100,200,300,'A',400,500]

28
Defining functions

 In Python, you define a new function by using the “def”


keyword.

def sayHello(name):
print(“Hello, ” + name)

sayHello(“Ahmed”)

Result :
Hello, Ahmed

29
Multiline strings

 You can make strings that include multiple lines by


using three double or single quotations, just like
you would in a comment.
str = “””To be or not to be
This is the question”””
print(str)

Result :
To be or not to be
This is the question

30
String slicing

 A string is a list of characters. So, you can use list


operations on it. You can access a certain character by
using square brackets with the index inside them.
str = “It’s-a me, Mario!”
print(str[1])

Result :
t

31
String slicing

 In Python, you can also get a subset of the array between


two indices by giving the starting index and ending index
(this index is excluded) with a colon between them. If you
don’t give any indices, it’s like saying you want all of the
string.
str = “It’s-a me, Mario!”
print(str[7:9])
print(str[:])

Result :
Me
It’s-a me, Mario! 32
String slicing

 You can also specify a skip in characters while using


the subset syntax.

str = “sdetcwryept”
print(str[::2])

Result :
secret

33
String slicing

 Another trick in Python lists is using a negative index.


Negative index are exactly like indices, but they
start counting from the end of the list.
str = “It’s-a me, Mario!”
print(str[-1])

Result :
!

34
String length

 To get the length of a string, you can use the len()


function. As you can guess, len() can also be used
on lists, since strings are lists.
str = “You can count on this string when you’re in trouble”
print(len(str))

Result :
51

35
Removing extra whitespace on
sides

 Keeping extra whitespace on the side of the text can


sometimes cause problems in your code, that’s
why we the use strip() function.
str = “ There are extra spaces on the sides ”
print(str)
print(str.strip())

Result :
There are extra spaces on the sides
There are extra spaces on the sides
36
Replacing characters in a string

 If you want to replace all instances in a string of a certain


character with another character, you can use the replace() function.
If you want to replace a pattern match with another character, you
can use sub() function from the re module.

str = “Wryng spelling” import re


str = str.replace(“y”, “o”) s = "I am a human being."
res_1 = re.sub('a', 'x', s)
print(str)
res_2 = re.sub('[a,I]','x',s)
print(res_1)
Result : print(res_2)
Wrong spelling
Result :
I xm x humxn being. 37
x xm x humxn being.
Splitting a string into a list of
strings

 If you want split a string into a list of strings based on a


certain character, you can do so by using the
split() function.
str = “Split up”
str_list = str.split(“ “)
print(str_list)

Result :
['Split', 'up']

38
String concatenation

 To concatenate two string, you use the + symbol


between two string.

str = “Let’s merge ”


another_str = “these two strings”
print(str + another_str)

Result :
Let’s merge these two strings

39
Opening files

 To open a file in Python, you use the open() function.

file = open(“text.txt“)

40
Opening files

 The open() function has several modes you can use.


Mode Description
r Read
w Write
a Append
t Text
b Binary

41
Reading files

 To read a file in Python, you use the open() function,


then the read() function.

file = open(“text.txt“)
print(file.read())

42
Reading files

 You can also read a line in a file by using readline(), or


read all lines by readlines() or by using for.

file = open(“text.txt“)
print(file.readline())
print(file.readlines())

43
Writing files

 You can write a new file by using the write() function.


If the file exists, the file will be
overwritten.
file = open(“text.txt“, “w”)
file.write(“New text”)

44
Writing files

 If you don’t want to delete the file and just want to


append to it, you give the parameter “a” to the
open() function.
file = open(“text.txt“, “a”)
file.write(“New text”)

45
Closing files

 You should always close your files after you’re done


with them. You can do that by using the close()
function.
file = open(“text.txt“, “a”)
file.write(“New text”)
file.close()

46
Closing files

 However, there’s an easier way to ensure that the file


automatically closer after you’re done with it, and
that’s by using the “with” statement
with open(“text.txt“, “a”) as file:
file.write(“New text”)

47
Installing new libraries

 Throughout the course, we’ll need to use external libraries. To


install Python libraries, we the “pip” tool. Usually, you’d need to
use the command line to use it, but you can use it in your IDE or
notebook by simply adding “!” before the command.

!pip install *name of library*

48
Installing new libraries

 If you want to do something in Python that doesn’t have


built- in function for, you’ll probably find a library for it.
Whenever you need a library like that, you can use PyPI
to search for it.
https://pypi.org/

49
Reading PDF files

 To read PDF files in Python, we’ll need to install a


library called PyPDF2.
!pip install PyPDF2

50
Reading PDF files

 To read a PDF file using the PyPDF2 library, you first


need to open the file, then you need to use the
PdfFileReader() function to read the file.

import PyPDF2

file = open(‘file.pdf’, ‘rb’)


pdf_reader = PyPDF2.PdfFileReader(file)

51
Extracting text from PDF files

 To read the text from the PDF file, you first need to get
the page you want to get the text from by using the
getPage() function. After that, you use the
extractText() function.
import PyPDF2

file = open(‘file.pdf’, ‘rb’)


pdf_reader = PyPDF2.PdfFileReader(file)
page = pdf_reader.getPage(0)
text = page.extractText()
52
Try it out yourself

 Code:
https://colab.research.google.com/drive/1UAtVuTLbWGg
WSwJvMYILiVTpBXs7HoYv

53
Task #3

 Write a Python program that reverses a string without


using any built-in functions.

54
Task #4

 Read the PyPDF2 documentation:


https://pythonhosted.org/PyPDF2/
 Make a Python program that opens a PDF file, reads it,
prints how many pages there are and loops
through each page while printing the page’s content.

55
Thank you for your attention!

56
References

 https://www.freecodecamp.org/news/learning-python-from-zero-to-hero-120ea540b567
/
 https://en.wikipedia.org/wiki/Python_(programming_language)
 https://www.w3schools.com/python/python_operators.asp
 https://www.learnpython.org/en/Basic_String_Operations
 https://www.w3schools.com/python/python_strings.asp
 https://www.w3schools.com/python/python_file_handling.asp

57

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy