Week 3
Basic Python 1
1
LING 300 - Topics in Linguistics: Introduction to Programming and Text Processing for Linguists
Week 3 Basic Python 1 1 Notes from Assignment 2 Whitespace is - - PowerPoint PPT Presentation
LING 300 - Topics in Linguistics: Introduction to Programming and Text Processing for Linguists Week 3 Basic Python 1 1 Notes from Assignment 2 Whitespace is invisible and therefore tricky e.g. top word = 46401 instances of Can
1
LING 300 - Topics in Linguistics: Introduction to Programming and Text Processing for Linguists
sed 's/ +/\n/g'
2
3
grep love shakes.txt > lovelines.txt wc -l lovelines.txt
grep love shakes.txt | wc -l
4
5
diff -y my_assignment_output.txt your_assignment_output.txt
6
7
['y', 2, False]
(6, ‘b’, 19.7)
'hello!' (next week) Set set Mapping dict{}
True, False
8
9
10
11
12
13
14
15
>>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... print('Negative!') ... elif x == 0: ... print('Zero!') ... else: ... print('Positive!') Positive!
16
>>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print(w, len(w)) ... cat 3 window 6 defenestrate 12
17
>>> for i in range(5): ... print(i) … 1 2 3 4
18
>>> for line in open('shakes.txt'): ... print(line) 1609 THE SONNETS by William Shakespeare
19
>>> # Fibonacci: sum of two elements defines the next ... a, b = 0, 1 >>> while a < 10: ... print(a, end=' ') ... a, b = b, a+b ... print('') ... 0 1 1 2 3 5 8
20
The body of function definitions and control flow elements must be indented by one level Recommended to be
. . . . or four spaces
21
>>> job_title = 'LINGUIST'
Char (or List Item) L I N G U I S T Index 1 2 3 4 5 6 7 Reverse Index
>>> job_title[3:-1] 'GUIS' # inclusive of start, not inclusive of end >>> job_title[:5] 'LINGU' # can leave off start or end
22
>>> s = ' my sTrInGggg!\n' >>> s = s.strip() >>> s 'my sTrInGggg!' >>> s = s.strip('!').strip('g') >>> s 'my sTrInG'
>>> s = s.lower() >>> s 'my string'
>>> s.find('str') 3
>>> s.replace('my','your') 'your string'
>>> s.startswith('balloon') False
23
>>> x = [1, 4, 9, 16] >>> x.append(9) >>> x [1, 4, 9, 16, 9]
>>> x.index(4) 1
>>> x.remove(9) >>> x [1, 4, 16, 9]
>>> x.pop() 9 >>> x [1, 4, 16]
24
my_list[3] = 'yes' my_str[3] = 'n'
>>> s = 'my string' >>> ' '.join(['your','string']) >>> s.split() 'your string' ['my', 'string']
25