0% found this document useful (0 votes)
25 views15 pages

Python difflib Example for Translation

The document discusses various Python programming concepts including functions, conditionals, loops, file processing, and importing modules. Some key points covered include defining functions, writing if/else conditional blocks, using for and while loops, reading/writing to files, and importing built-in and third-party modules. Examples are provided for each concept to demonstrate syntax and usage.

Uploaded by

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

Python difflib Example for Translation

The document discusses various Python programming concepts including functions, conditionals, loops, file processing, and importing modules. Some key points covered include defining functions, writing if/else conditional blocks, using for and while loops, reading/writing to files, and importing built-in and third-party modules. Examples are provided for each concept to demonstrate syntax and usage.

Uploaded by

Pamba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Functions and Conditionals

In this section, you learned to:

 Define a function:

1. def cube_volume(a):
2. return a * a * a

 Write a conditional block:
1. message = "hello there"
2.  
3. if "hello" in message:
4. print("hi")
5. else:
6. print("I don't understand")

 Write a conditional block of multiple


conditions:
1. message = "hello there"
2.  
3. if "hello" in message:
4. print("hi")
5. elif "hi" in message:
6. print("hi")
7. elif "hey" in message:
8. print("hi")
9. else:
10. print("I don't understand")
 Use the  and  operator to check if both
conditions are True at the same
time:
1. x = 1
2. y = 1
3.  
4. if x == 1 and y==1:
5. print("Yes")
6. else:
7. print("No")

Output is  Yes  since both  x  and  y  are 1.

 Use the  or  operator to check if at least one


condition is True:
1. x = 1
2. y = 2
3.  
4. if x == 1 or y==2:
5. print("Yes")
6. else:
7. print("No")

Output is  Yes  since  x  is 1.

 Check if a value is of a particular type with:


1. isinstance("abc", str)
2. isinstance([1, 2, 3], list)

or
1. type("abc") == str
2. type([1, 2, 3]) == lst

Processing User Input

In this section, you learned that:

 A Python program can get user input via


the  input  function:

 The input function halts the execution of


the program and gets text input from the user:

1. name = input("Enter your name: ")

 The input function converts any input to a string, but you


can convert it back to int or float:
1. experience_months = input("Enter your
experience in months: ")
2. experience_years = int(experience_months) / 12

 You can format strings with (works both on Python 2 and


3):
1. name = "Sim"
2. experience_years = 1.5
3. print("Hi %s, you have %s years of experience."
% (name, experience_years))
Output:  Hi Sim, you have 1.5 years of experience.
 You can also format strings with:

1. name = "Sim"
2. experience_years = 1.5
3. print("Hi {}, you have {} years of
experience".format(name, experience_years))

Output:  Hi Sim, you have 1.5 years of experience.

For Loop Over a Function

Note that using loops, you can call any function multiple times,
even your own functions. Let's suppose we defined this
function:

1. def celsius_to_kelvin(cels):
2. return cels + 273.15

That is a function that gets a number as input, adds 273.15 to it


and returns the result. A for loop allows us to execute that
function over a list of numbers:
1. monday_temperatures = [9.1, 8.8, -270.15]
2.  
3. for temperature in monday_temperatures:
4. print(celsius_to_kelvin(temperature))

The output of that would be:


282.25
281.95
3.0
So, in the first iteration  celsius_to_kelvin(9.1)  was
executed, in the second  celsius_to_kelvin(8.8)  and in the
third  celsius_to_kelvin(-270.15) .
That's just something to keep in mind.

Dictionary Loop and String


Formatting

You can combine a dictionary for loop with string formatting to


create text containing information from the dictionary:

1. phone_numbers = {"John Smith": "+37682929928",


"Marry Simpons": "+423998200919"}
2.  
3. for pair in phone_numbers.items():
4. print("{} has as phone number
{}".format(pair[0], pair[1]))

Another (better) way to do it::

1. phone_numbers = {"John Smith": "+37682929928",


"Marry Simpons": "+423998200919"}
2.  
3. for key, value in phone_numbers.items():
4. print("{} has as phone number
{}".format(key, value))

In both cases the output is:


Output:

John Smith has as phone number +37682929928


Marry Simpons has as phone number +423998200919

Loops

In this section, you learned that:

 For loops are useful for executing a command over a


large number of items.
 You can create a for loop like so:
1. for letter in 'abc':
2. print([Link]())

Output:

A
B
C
 The name after  for  (e.g.  letter ) is just a variable name

 You can loop over dictionary keys:


1. phone_numbers = {"John
Smith":"+37682929928","Marry
Simpons":"+423998200919"}
2. for value in phone_numbers.keys():
3. print(value)

Output:
John Smith
Marry Simpsons
 You can loop over dictionary values:
1. phone_numbers = {"John
Smith":"+37682929928","Marry
Simpons":"+423998200919"}
2. for value in phone_numbers.values():
3. print(value)

Output:

+37682929928
+423998200919
 You can loop over dictionary items:
1.phone_numbers = {"John
Smith":"+37682929928","Marry
Simpons":"+423998200919"}
[Link] key, value in phone_numbers.items():
3. print(key, value)

Output: 

('John Smith', '+37682929928')


('Marry Simpons', '+423998200919')

 While loops will run as long as a condition is true:


[Link] [Link]() <
[Link](2090, 8, 20, 19, 30, 20):
2. print("It's not yet 19:30:20 of 2090.8.20")

The loop above will print out the string inside print() over
and over again until the 20th of August, 2090.
List Comprehensions

In this section, you learned that:

 A list comprehension is an expression that creates a list by


iterating over another container.

 A basic list comprehension:
1.[i*2 for i in [1, 5, 10]]

Output:  [2, 10, 20]


 List comprehension with if condition:
1.[i*2 for i in [1, -2, 10] if i>0]

Output:  [2, 20]


 List comprehension with an if and else condition:
1.[i*2 if i>0 else 0 for i in [1, -2, 10]]

Output:  [2, 0, 20]

More on Functions
In this section, you learned that:

 Functions can have more than one parameter:


1. def volume(a, b, c):
2. return a * b * c

 Functions can have default parameters (e.g.  coefficient ):


1. def converter(feet, coefficient = 3.2808):
2. meters = feet / coefficient
3. return meters
4.  
5. print(converter(10))

Output:  3.0480370641306997
Arguments can be passed as non-keyword (positional) arguments
(e.g.  a ) or keyword arguments (e.g.  b=2  and  c=10 ):
1. def volume(a, b, c):
2. return a * b * c
3.  
4. print(volume(1, b=2, c=10))

 An *args parameter allows the  function to be called with an


arbitrary number of non-keyword arguments:
1. def find_max(*args):
2. return max(args)
3. print(find_max(3, 99, 1001, 2, 8))

Output:  1001
 An **kwargs parameter allows the function to be called with an
arbitrary number of keyword arguments:
1. def find_winner(**kwargs):
2. return max(kwargs, key = [Link])
3.  
4. print(find_winner(Andy = 17, Marry = 19, Sim = 45, Kae = 34))

Output:  Sim
 Here's a summary of function elements:
File Processing
In this section, you learned that:

 You can read an existing file with Python:


1. with open("[Link]") as file:
2. content = [Link]()

 You can create a new file with Python and write some text on it:


1. with open("[Link]", "w") as file:
2. content = [Link]("Sample text")

 You can append text to an existing file without overwriting it:


1. with open("[Link]", "a") as file:
2. content = [Link]("More sample text")

 You can both append and read a file with:


1. with open("[Link]", "a+") as file:
2. content = [Link]("Even more sample text")
3. [Link](0)
4. content = [Link]()

Imported Modules
In this section, you learned that:

 Builtin objects are all objects that are written inside the Python
interpreter in C language.
 Builtin modules contain builtins objects.
 Some builtin objects are not immediately available in the global
namespace. They are parts of a builtin module. To use those objects
the module needs to be imported first. E.g.:
1. import time
2. [Link](5)
 A list of all builtin modules can be printed out with:
1. import sys
2. sys.builtin_module_names
 Standard libraries is a jargon that includes both builtin modules
written in C and also modules written in Python.
 Standard libraries written in Python reside in the Python installation
directory as .py files. You can find their directory path with  [Link] .
 Packages are a collection of .py modules.
 Third-party libraries are packages or modules written by third-party
persons (not the Python core development team).
 Third-party libraries can be installed from the terminal/command
line:
Windows:

pip install pandas  or use  python -m pip install pandas  if that doesn't
work.
 Mac and Linux:

pip3 install pandas  or use  python3 -m pip install pandas  if that doesn't
work.

Solution: Making Version 1.2 of


the Program
Lines 8 and 9 were added to make sure the program returns the definition
of words that start with a capital letter (e.g., Delhi or Texas):
1. import json
2. from difflib import get_close_matches
3. data = [Link](open("[Link]"))
4. def translate(w):
5. w = [Link]()
6. if w in data:
7. return data[w]
8. elif [Link]() in data: #if user entered "texas" this will check for "Texas" as
well.
9. return data[[Link]()]
10. elif len(get_close_matches(w, [Link]())) > 0:
11. yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " %
get_close_matches(w, [Link]())[0])
12. if yn == "Y":
13. return data[get_close_matches(w, [Link]())[0]]
14. elif yn == "N":
15. return "The word doesn't exist. Please double check it."
16. else:
17. return "We didn't understand your entry."
18. else:
19. return "The word doesn't exist. Please double check it."
20.  
21. word = input("Enter word: ")
22. output = translate(word)
23. if type(output) == list:
24. for item in output:
25. print(item)
26. else:
27. print(output)

You can read the comments I included in the code: I have added another
conditional in lines 8 and 9. The  [Link]()  method will convert the first
letter to uppercase and the rest to lowercase. If the program didn't find
anything for "texas" in the first conditional in lines 6 and 7, then this
conditional will try to search for "Texas". Even if the user entered "TEXAS"
this conditional will convert it to "Texas".

Making Version 1.2 of the


Program
I added lines 10 and 11 to make sure the program returns the definition of
acronyms (e.g., USA or NATO.)
1. import json
2. from difflib import get_close_matches
3. data = [Link](open("[Link]"))
4. def translate(w):
5. w = [Link]()
6. if w in data:
7. return data[w]
8. elif [Link]() in data:
9. return data[[Link]()]
10. elif [Link]() in data: #in case user enters words like USA or NATO
11. return data[[Link]()]
12. elif len(get_close_matches(w, [Link]())) > 0:
13. yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " %
get_close_matches(w, [Link]())[0])
14. if yn == "Y":
15. return data[get_close_matches(w, [Link]())[0]]
16. elif yn == "N":
17. return "The word doesn't exist. Please double check it."
18. else:
19. return "We didn't understand your entry."
20. else:
21. return "The word doesn't exist. Please double check it."
22. word = input("Enter word: ")
23. output = translate(word)
24. if type(output) == list:
25. for item in output:
26. print(item)
27. else:
28. print(output)

More SQL Statements


In the example you just saw, we used the following SQL statement in our Python
code:
1. query = [Link]("SELECT * FROM Dictionary WHERE Expression = 'rain'")

That statement retrieved all the rows of the Dictionary table where the value of the
column Expression was rain. The string inside [Link]() is SQL code that
Python sends to the database. The database understands that kind of language.
Here are some more examples of SQL queries that you can try out from within
your Python script just like we did previously:

 Get all rows where the value of the column Expression starts with r:
1. "SELECT * FROM Dictionary WHERE Expression  LIKE 'r%'"

 Get all rows where the value of the column Expression starts with rain:
1. "SELECT * FROM Dictionary WHERE Expression  LIKE 'rain%'"

 All rows where the length of the value of the column Expression is less than
four characters:
1. "SELECT * FROM Dictionary WHERE length(Expression) < 4"

 All rows where the length of the value of the column Expression is four
characters:
1. "SELECT * FROM Dictionary WHERE length(Expression) = 4"
 All rows where the length of the value of the column Expression is greater
than 1 but less than 4 characters:
1. "SELECT * FROM Dictionary WHERE length(Expression) > 1 AND length(Expression) < 4"

 All rows of column Definition where the value of the column Expression


starts with r:
1. "SELECT Definition FROM Dictionary WHERE Expression LIKE 'r%'"

Loading JSON Files


In  the previous lecture, you learned that you can load a CSV file with this
code:
1. import pandas
2. df1 = pandas.read_csv("[Link]")

Try loading the  [Link]  file for this exercise


using  read_json  instead of  read_csv .
The [Link] file can be found inside the [Link] file
attached in the previous lecture.

Note
We are going to use  Nominatim()  in the next video.  Nominatim()  currently has
a bug. To fix this problem, whenever you see these lines in the next video:
1. from [Link] import Nominatim
2. nom = Nominatim()

change them to these


1. from [Link] import ArcGIS
2. nom = ArcGIS()

The rest of the code remains the same.


Note
In the next lecture, I use this in the code:

tiles = "Mapbox Bright"


Please use this instead:

tiles = "Stamen Terrain"


Mapbox Bright and Stamen Terrain are both types of basemaps, but
Mapbox Bright doesn't work anymore. Stamen Terrain works great, and you
will see it creates a beautiful relief map.

Common questions

Powered by AI

A for loop can be used with a dictionary in Python to iterate over its keys, values, or key-value pairs. This allows you to perform operations or extract information systematically. For example, to print each key and its corresponding value, you can use: ``` phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"} for key, value in phone_numbers.items(): print("{} has as phone number {}".format(key, value)) ``` This snippet will output each contact's name followed by their phone number .

Multiple conditions in a Python conditional block can be handled using 'elif' to check for alternative conditions if the initial 'if' condition is not satisfied. For example: ``` message = "hello there" if "hello" in message: print("hi") elif "hi" in message: print("hi") elif "hey" in message: print("hi") else: print("I don't understand") ``` This block checks for various greetings and outputs 'hi' if any recognized term is within the message; otherwise, it outputs "I don't understand" .

In Python, **kwargs allows a function to accept an arbitrary number of keyword arguments. This facilitates flexibility when the exact number of input arguments is unknown. For example: ``` def find_winner(**kwargs): return max(kwargs, key=kwargs.get) print(find_winner(Andy=17, Marry=19, Sim=45)) # Output: Sim ``` Here, find_winner uses **kwargs to receive any number of keyword arguments representing names and scores, returning the key with the highest value .

Standard Python libraries consist of both built-in modules written in C and modules written in Python that reside in the Python installation directory. These libraries don't require installation. You can import them directly, e.g., 'import time'. Third-party libraries, however, are developed by non-core Python developers and need installation via package managers like pip, e.g., 'pip install pandas' on Windows or 'pip3 install pandas' on Mac/Linux .

The 'or' operator in Python allows for evaluating conditions such that it returns True if at least one condition is true. For example: ``` x = 1 y = 2 if x == 1 or y == 2: print("Yes") else: print("No") ``` In this code, the output is "Yes" because even though both conditions are technically true, the 'or' operator ensures the block executes if any single condition is satisfied .

Reading and writing files in Python is done using the 'open' function with the appropriate mode: 'r' for reading, 'w' for writing, and 'a' for appending. For appending text, consider the following example: ``` with open("file.txt", "a") as file: file.write("More sample text") ``` This snippet opens 'file.txt' in append mode, adding "More sample text" to the end of the file without removing existing content .

SQL queries integrated within Python scripts are often used for database interactions, such as data retrieval or modification. Common use cases include fetching filtered datasets or inserting data. Queries can be structured in Python using functions like 'execute' from database adapters. Example queries include: ``` # Retrieve rows starting with 'r' query = cursor.execute("SELECT * FROM Dictionary WHERE Expression LIKE 'r%'") # Retrieve rows of specific length query = cursor.execute("SELECT * FROM Dictionary WHERE length(Expression) < 4") ``` These queries leverage SQL 'LIKE' and 'length' functions to interact with databases, allowing Python scripts to perform complex data manipulations efficiently .

To make a Python program interactive for word matching, you can use input functions to dynamically receive words, then use conditional logic and functions to check for matches in a dataset. This is achieved by converting inputs to lowercase, checking against a dataset, using title-case for proper nouns, and offering suggestions for close matches. For instance: ``` def translate(w): if w in data: return data[w] elif w.title() in data: return data[w.title()] elif w.upper() in data: return data[w.upper()] # Suggest alternatives using close matches ``` This function will actively seek matches for input 'w' across various cases and offer suggestions based on similarity, enhancing user engagement .

The 'input' function in Python halts the execution of the program to receive text input from the user. Every input taken by this function is converted to a string by default, but it can be converted back to integers or floats as needed. For instance, you can use 'int' or 'float' to convert the string input to numerical data types for further computations .

List comprehensions provide a concise way to create lists in Python. They are advantageous because they lead to more readable and expressive code compared to traditional loops. They support incorporating conditions directly. Here are examples: - Basic comprehension: `[i*2 for i in [1, 5, 10]]` results in `[2, 10, 20]`. - With an 'if' condition: `[i*2 for i in [1, -2, 10] if i>0]` results in `[2, 20]`. - With both 'if' and 'else': `[i*2 if i>0 else 0 for i in [1, -2, 10]]` results in `[2, 0, 20]` .

You might also like