1 / 45

Programming for Linguists

Programming for Linguists. An Introduction to Python 6 /12/2012. Overview. Exercises Fruitful vs. Void Functions Return Statement Recursion Lists While Statement Introduction to Regular Expressions. Exercises.

talen
Download Presentation

Programming for Linguists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming for Linguists An Introduction to Python6/12/2012

  2. Overview • Exercises • Fruitful vs. Void Functions • Return Statement • Recursion • Lists • While Statement • Introduction to Regular Expressions

  3. Exercises Oef. 1defprintSentence(sentence): print sentence.upper( ) print sentence.lower( ) print sentence.title( )printSentence(“hallo iedereen”)

  4. Oef 2.defcheckIndex(sent, let):highestI = sent.rfind(let)lowestI= sent.find(let) print ‘higest index’, highestI print ‘lowest index’, lowestI for s in sent: if sent.index(s) > 3 and s == let: sent = sent[:3] + sent[3:].replace(s, ‘3’) print sentcheckIndex(“Hello iedereen”, “e”)

  5. Oef 3.deftkofschip(verb): ifverb.endswith ("t") or verb.endswith("k") or verb.endswith ("f") or verb.endswith("s") or verb.endswith("c") or verb.endswith("h") or verb.endswith("p"): print verb+"te" else: print verb+"de" tkofschip(“lach”)

  6. Oef 4.def change( ): name = raw_input(“What's your name? ”) name = name.lower( ) name = name.replace(‘a’, ‘4’)name = name.replace(‘e’, ‘3’) name = name.replace(‘i’, ‘1’)name = name.replace(‘o’, ‘0’) print namechange( )

  7. Fruitful vs. Void Functions defwordLength(word): print len(word) word1 = wordLength(“hallo”)print word1type(word1) def wordLength2(word):returnlen(word) word2 = wordLength2(“hallo”)print word2type(word2)

  8. Fruitful functions: • return a value • result = int, str, float, function,… • you can work with this value in the rest of your script • often contain the return-statement • Void functions: • do not return a value • result = NoneType • all operations in the function are lost

  9. Return statement • Translation: “return immediately from the function and use the following expression as a return value” defwl(word): return len(word) print len(word) wl(“kast”) def wl2(word): print len(word) return len(word) wl2(“kast”)

  10. You can use multiple return statements defabsoluteValue(x): if x >= 0: return x else: return –x absoluteValue(–1)

  11. You can return a value, a variable, a function, a boolean expression • As soon as a return statement executes, the function terminates • Code that appears after a return statement = dead code

  12. Ask the user to enter his/her age. Write a functionthat takes the result as an argumentand returns Trueif the user is over 18 andFalseif the user is under 18. Thenwriteanif-statementthat prints “Pass” when the result of the function is True and “Stop” if the result is False.

  13. >>>input = raw_input(“Welcome. How old are you? ”) >>>defageCheck(user_age):user_age = int(user_age) if user_age >= 18: return True else: return False >>> if ageCheck(input) == True: print “Pass” else: print “Stop”

  14. Recursion • As we saw: one function can call another • A function can also call itself • A function that calls itself = recursive • The process = recursion

  15. Try this:def countdown(nr): ifnr<=0: print ‘Happy Newyear!’ else: print nrnr = nr - 1 countdown(nr)countdown(10)

  16. Infinite Recursion • If a recursion never reaches a base case, it goes on making recursive calls forever the program never terminates • Generally not a good idea • Python reports an error message when the maximum recursion depth is reached

  17. e.g.def recurse( ): recurse( )recurse( )

  18. Lists • A list is a sequence of values • The valuescanbe of any type • The values = elements/items • A list is always in between[ ] • To create a new list:l1 = [10, “cheese”, 5.6, “this is a sentence”]

  19. A list can contain another list (nested list):l2 = [‘hello’, 15, [‘my name is’, ‘X’]] • A list also has an indexprint l2[0]print l2[– 1]print l2[1:]print l2.index(15) • you can change existing lists>>>l2[2] = 10>>>print l2[‘hello’, 15, 10]

  20. A list index works the sameway as a string index: • any integer expressioncanbeused as an index • ifyoutry to readorwritean element that does notexist, yougetanIndexError • ifan index has a negativevalue, itcountsbackwardfrom the end of the list • the in operator alsoworksonlists

  21. Working with Lists • Creating an empty list empty_list = [ ] • Traversing a list: words = [‘work’, ‘run’, ‘play’, ‘jump’]forwinwords: print w Thefor loop traverses the list andperformsan action on eachelement

  22. List Operations • The + operator concatenateslists • the * operator repeats a list a givennumber of times • The slice operator [n:m] givesyou a slice of the list

  23. Example list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list3 = list1 + list2 print list3 print list1*2 print list1[1:3]

  24. Addingelementstolists • one elementlist1 = [‘a’, ‘b’, ‘c’]list1 + ‘d’list1 += ‘d’print list1list1 = list1 + [‘e’]print list1list1.append(‘f’)print list1list1.extend(‘g’)print list1

  25. more thanone elementlist1 = [‘a’, ‘b’, ‘c’]list1 +=[‘d’, ‘e’, ‘f’]print list1list1.append([‘g’, ‘h’, ‘i’])print list1list1.extend([‘j’, ‘k’, ‘l’])print list1 • But list1.append(‘g’, ‘h’, ‘i’)list1.extend(‘g’, ‘h’, ‘i’)

  26. Pay attention! • Whenyouonlyaddone element +=item ,.append(item), .extend(item)and+[item] return the sameresult • Whenyouadda list .append(list)returns a nested list!

  27. Deleting elements from a listlist1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] • using the index in the list list1.pop(1) print list1del list1[0] print list1 • using the elements in the list list1.remove(‘d’) print list1

  28. popmethod  modifies the list and returns the removed element • delmethod modifies the list without returning the removedelement • removemethod ifyou do notknow the index of the element

  29. Pay attention!words = [‘ha’,‘funny’, ‘ha’, ‘ha’]words.remove(‘ha’)print words • .remove( ) only deletes the first occurrence of the item in the list • again details: pay attention to where your list variable should comelist.pop(index) del list[index]list.remove(item)

  30. Some other methods • list.count( ) counts the number of items • list.sort( )sorts the list bynumber/alphabetically • list.insert(index, item) places the item at the given index in the list • list.reverse( ) reverses the list

  31. From String to List • From a word to a list of letters: list( ) functions = “spam”print list(s)[‘s’, ‘p’, ‘a’, ‘m’] • From a sentence to a list of words: .split( )functions = “This is a sentence”print s.split( )[‘This’, ‘is’, ‘a’, ‘sentence’]

  32. The split( ) function splits on white spaces, but can also be used to split a string on other characters s = “spam;spam;spam”print s.split(“;”)[‘spam’, ‘spam’, ‘spam’] • “;” is called the delimiterin this case

  33. From List to String • Join( ) is the inverse of split( )l = [‘this’, ‘is’, ‘a’, ‘sentence’]delimiter = “ ”delimiter.join(l)“this is a sentence”

  34. Rewriteyourtkofschipfunctionusing a list and return statements.

  35. deftkofschip(verb): letters = [‘t’, ‘k’, ‘f’, ‘s’, ‘c’, ‘h’, ‘p’]ifverb[-1] in letters: return verb + ‘te’else: return verb + ‘de’tkofschip(‘speel’)tkofschip(‘schop’)

  36. The While Statement • used to perform identical or similar tasks def countdown(nr):whilenr > 0: print nrnr = nr – 1 print “Happy Newyear!”countdown(10)

  37. Mind the difference in indentation between the statements inside and outside the while statement ! • The statements inside the body should change the value of one or more variables so that the condition becomes False at a certain point • If a loop goes on forever = infinite loop • You can use the break statement to jump out of the loop

  38. This program will echo the keyboard input until the user types “done” while True: line = raw_input (“> ”)if line == “done”: break print line

  39. Regular Expressions • Touseregularexpressions in Python we need to import the re library(at the beginning of the script)import re

  40. Some Basic Regular Expression Meta-characters • . Wildcard, matches anycharacter • ^abc Matches somepattern abc at the start of a string • abc$ Matches somepattern abc at the end of a string • [abc] Matches one of a set of characters • [A-Z0-9] Matches one of a range ofcharacters

  41. a|b|c Matches one of the specifiedstrings (disjunction) • * Zero or more of the previous item(s) • + One or more of the previous item(s) • ? Zero orone of the previous item(s) (i.e.optional) • {n} Exactlynrepeatswheren is anon-negative integer • {n,} At leastnrepeats

  42. {,n} No more thannrepeats • {m,n} At leastmand no morethannrepeats • a(b|c)+ Parentheses thatindicate the scope of the operatorse.g.w(i|e|ai|oo)t matches wit, wet, waitand woot • <.*> Matches anytoken • In general, whenusingregularexpressionsit is best to user'...' before the regularexpressions

  43. Counting all vowels in a given word:word='supercalifragilisticexpialidocious' vowels = re.findall(r'[aeiou]', word)nr_vowels = len(vowels) • The re.findall( ) functionfinds all (non-overlapping) matches of the givenregularexpression

  44. You can find a list of all regular expressions operations in Python on: http://docs.python.org/library/re.html • Exercises for next week on Blackboard

  45. Thank you!

More Related