Text, Web And Media Analytics
Week 2 – Lecture
Python Introduction
Copyright By PowCoder代写 加微信 powcoder
Yuefeng Li | Professor
School of Electrical Engineering and Computer Science
Queensland University of Technology
S Block, Level 10, Room S-1024, Gardens Point Campus
ph 3138 5212 | email
1. Installing Python
2. Python commands
3. Strings and Lists
4. Program and functions
5. Dictionaries, Structuring Data and Classes
6. Reading and Writing Files
7. Web Scraping
Why Python?
Python is an easy to learn, powerful programming language for text process.
It has efficient high-level data structures and a simple but effective approach to object-oriented programming.
Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
Y Li: IFN647 week 2 lecture notes
1. Installing Python
http://python.org/downloads/
Python installers for 64-bit or 32-bit computers (see system in the Control Panel, or hardware in system reports of OS X)
Starting IDLE
Python GUI
Y Li: IFN647 week 2 lecture notes
Y Li: IFN647 week 2 lecture notes
2. Python commands
Start the interpreter and wait for the primary prompt, >>>
Expression syntax is straightforward: the operators +, -, *, /, % (remainder) and ** (calculate powers) work just like in other languages; parentheses (()) can be used for grouping.
They can be enclosed in single quotes (‘…’) or double quotes (“…”) with the same result, where special characters are escaped with backslashes \.
The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes.
The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters.
>>> s = ‘First line.\nSecond line.’ # \n means newline
>>> s # without print(), \n is included in the output
‘First line.\nSecond line.’
>>> print(s) # with print(), \n produces a new line
First line.
Second line.
Escape character Prints as
\’ single quote
\” double quote
\n newline
\\ backslash
如果字符串包含单引号而不包含双引号,则字符串用双引号括起来,否则用单引号括起来。
3. Strings and Lists
>>> 3 * ‘un’ + ‘ium’
‘unununium’
>>> ‘Py’ ‘thon’
>>> word = ‘Python’
>>> word[0] # character in position 0
>>> word[-1] # last character
>>> word[2:5] # from position 2 to
>>> word[:2] # from beginning to 2
>>> len(word)
n. (设备、机器的)操作员;经营者运算符号
String Methods
>>> spam = ‘Hello world!’
>>> print(spam.upper())
HELLO WORLD!
>>> spam.lower()
‘hello world!’
>>> spam.isupper()
>>> spam.isalpha()
>>> spam=spam.upper()
>>> spam.istitle()
>>> spam = ‘Hello World!’
>>> spam.istitle()
>>> spam.startswith(‘He’)
>>> ‘-‘.join([‘My’, ‘Name’, ‘is’, ‘John’])
‘My-Name-is-John’
>>> ‘My-Name-is-John’.split(‘-‘)
[‘My’, ‘Name’, ‘is’, ‘John’]
>>> squares = [1, 4, 9, 16, 25]
>>> squares[0]
>>> squares[-1]
>>> squares[-3:] # get a new list
[9, 16, 25]
>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64 # replace the wrong value
[1, 8, 27, 64, 125]
>>> cubes.append(216) # add the cube of 6
[1, 8, 27, 64, 125, 216]
>>> letters = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]
>>> letters[2:5] = [‘C’, ‘D’, ‘E’]
>>> letters
[‘a’, ‘b’, ‘C’, ‘D’, ‘E’, ‘f’, ‘g’]
>>> letters[2:5] = []
>>> letters
[‘a’, ‘b’, ‘f’, ‘g’]
>>> len(letters)
>>> a = [‘a’, ‘b’, ‘c’]
>>> n = [1, 2, 3]
>>> x = [a, n]
[[‘a’, ‘b’, ‘c’], [1, 2, 3]]
4. Program and functions
The First Program
Type the instructions into a file editor OR in IDLE, select File ->
# this program says hello and asks for your name
print(‘Hello’)
print(‘What\’s your name?’)
yourName=input()
print(‘It is good to meet you,’ + yourName)
print(‘The length of your name is\n’)
print(len(yourName))
Save (as) your file
Run -> Run module
OR using Jupyter
Assignment statements: x = y
Boolean values: True, False
Comparison operators (==, !=, < >, <=, >=)
Boolean operators: and, or, not
If statements
for Statements
While statements
break and continue Statements
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
The continue statement, also borrowed from C, continues with the next iteration of the loop:
Please guess the outputs?
Importing Modules
A module can contain executable statements as well as function definitions.
Also, all Python programs can call built-in functions (a basic set, e.g., input(), print(), len(), int(), float(), str())
Python also comes with the standard library (a set of modules, e.g., math, random, sys, os)
The import keyword (e.g., import random; the we can use random.randint(a, b) function to get a random number between a and b)
Standard Modules: sys
dir() function is used to find out which names a module defines.
Packages are a way of structuring Python’s module namespace by using “dotted module names”.
For example, the module name A.B designates a submodule named B in a package named A.
Users of the package can import individual modules from the package, for example:
import sound.effects.echo #It must be referenced with its full name, or
from sound.effects import echo #makes it without its package prefix
Call the function to test it
Local and Global Scope
Local variables are parameters or variables that are used in a local scope, e.g., x, y and n used in fib are said to exist in that function’s local scope.
Otherwise, they are global variables.
Local variables cannot be used in the global scope or in other local scopes.
Global ones can be read from a local scope.
Exception Handling
An error, or exception, can crash the entire program.
Errors can be handled with try and except statements.
5. Dictionaries, Structuring Data & Classes
A dictionary is a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
A pair of braces creates an empty dictionary: {}.
Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
Unlike list, items in dictionaries are unordered. So, dictionaries cannot be sliced like lists.
>>> spam = [‘cats’, ‘dog’, ‘moose’]
>>> bacon= [‘dog’, ‘moose’, ‘cats’]
>>> spam==bacon
>>> dspam = {‘cats’:2, ‘dog’:3, ‘moose’:10}
>>> dbacon= {‘dog’:3, ‘moose’:10, ‘cats’:2}
>>> dspam == dbacon
Review Methods for List objects
list.append(x) Add an item to the end of the list.
list.extend(iterable) Extend the list by appending all the items from the iterable.
list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert.
list.remove(x) Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
list.pop([i]) Remove the item at the given position in the list and return it.
list.clear() Remove all items from the list. Equivalent to del a[:].
list.index(x[, start[, end]]) Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
list.count(x) Return the number of times x appears in the list.
list.sort(key=None, reverse=False) Sort the items of the list in place.
list.reverse() Reverse the elements of the list in place.
list.copy() Return a shallow copy of the list. Equivalent to a[:].
List Comprehensions
List comprehensions provide a concise way to create lists.
The following is an example to create a list: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = []
for x in range(10):
squares.append(x**2)
OR equivalently (list comprehension):
squares = [x**2 for x in range(10)]
The following program combines the elements of two lists x and y if they are not equal:
combs = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
Write a list comprehension to create combs using two list x = [1,2,3] and y = [3,1,4] as follows:
Main operations on a dictionary
They are storing a value with some key and extracting the value given the key.
It is also possible to delete a key:value pair with del.
If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
The dict() constructor builds dictionaries directly from sequences of key-value pairs.
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions.
keys(), values() and items() methods
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using these methods.
Classes provide a way of bundling data and functionality together.
Python classes provide all the standard features of Object-Oriented Programming
Class Definition Syntax
Class objects support two kinds of operations: attribute references and instantiation.
Attribute references use the standard syntax: obj.name
The instantiation creates an empty object.
A specific initial state, define a special method named __init__().
class ClassName:
Example of Classes
Linked List
Define a Node class that includes two attributes: data and next
Class Linkedlist
Attribute: head
Mthods: insert, lprint
Please use the two classes to create a linked list:
Then print the list as
A –> B –> C
6. Reading and Writing Files
A file has two key properties: a filename and a path (root in window is c:\, and on OS X or Linux, the root is /)
Creating string for filenames
os.path.join(‘usr’, ‘bin’, ‘spam’)
In window, it will be ‘usr\\bin\\spam’ # backslash needs to be escaped; in OS X or Linux, it will be ‘usr/bin/spam’
os.path Module
Get and change the current working directory
>>> os.getcwd()
‘/Users/li3/Desktop/2020/Python code’
>>> os.chdir (‘/Users/li3/Desktop’)
>>> os.getcwd()
‘/Users/li3/Desktop’
Other commands
Os.makedirs()
Os.path.abspath()
Os.path.getsize()
Os.path.exists()
Open and Read files
Open() function returns a File object (Close() is used to close the file)
import glob #open(file_) for file_ in glob.glob(“*.xml”)
Read() or write() methods on the File object.
All paragraphs that start with ‘'
Example File 6146.xml
Paragraphs separated by newline
Y Li: ITB(N)740 Week 13
Y Li: ITB(N)740 Week 13
7. Web Scraping
The webbrowser module comes with Python and opens a browser to a page.
>>> import webbrowser
>>> webbrowser.open(‘http://inventwithpython.com/’)
Download a Web page
install requests module
pip install requests
Requests.get() function
Raise_for_status() is used to
stop if an error happens
Processing HTML
This week workshop is abut “Python Basic”. A Lab based workshop.
You may be required to research some commands or algorithms supervised by your tutor.
I strongly recommend you to do all practical exercises.
If you have problems with the exercises, please let me or your tutor know.
References
[1] https://docs.python.org/3/tutorial/
[2] Al Sweigart, Automate the boring stuff with Python, 2015
[3] K. A. Lambert, Foundations of Python: data structures, Cengage Learning PTR, 2014.
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com