Python Flashcards

1
Q

In Python, data = [6, 8, 10, 12];

put data into an np array?

A

import np

MyArray = np.array(data)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

In Python add dict1 to dict 2?

A

dict2.update(dict1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

In Python, create a dict that pairs keys and values? (keys and values are variables)

A

dict(zip(keys, values))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

In Python and numpy:
arr_slice = arr[5:8]
arr_slice[1] = 12345

What is the result?

A

arr[6] equals 12345 (in the original object)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a python list comprehension to find all words in TEXT that are longer than 5 characters and appear at least 5 times?

A

[w for w in set(TEXT) if len(w) > 5 and FreqDist(TEXT)[w] >=5]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

With NLTK, when tagging, what is a way to address the trade-off between accuracy and coverage?

A

Start with a tagger that is more accurate and back-off to a tagger that has greater coverage

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

In python, how can you reverse a dictionary and why do it?

A

How:
nltk.Index((value, key) for (key, value) in oldDict.items())

Why:

  • Reverse lookup is faster
  • dict() won’t deal with multiple values
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Using NLTK and the brown corpus, how do you create a conditional frequency distribution based on genre?

A

ConditionalFreqDist((genre, word)
for genre in brown.categories()
for word in brown.words(categories = genre))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

arr = np.array([1, 2, 3], [4, 5, 6])

What does arr[0,2] return?

A

The same as arr[0][2], which is 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

arr = np.array([1, 2, 3], [4, 5, 6])

What does arr[0][2] return?

A

The same as arr[0,2], which is 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

In iPython, 2 quick ways to time a function?

A

1) %timeit

2) %time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

In Python, return an object’s True or False?

A

bool(object)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

In Python, return the value of ‘a’ from myDict while deleting the key, value pair?

A

myDict.pop(‘a’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

In Python, load numpy?

A

import numpy as np

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

In iPython, look up magic words?

A

%.[TAB]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

In Python’s interpreter, return list of attributes & methods of myObject?

A

myObject.[TAB]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

In, iPython, what does this return?

‘numpy.load?’

A

All numpy functions that have load as part of the name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

In Python, s = ‘hello’

s[::-1]?

A

olleh

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

In Python, what does the following return if x = 30?

‘Yes’ if x > 10 else ‘No’

A

‘Yes’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

In Python, s = ‘hello’

What does the following return?

For i, value in enumerate(s):
print(value)

A
h
e
l
l
o
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

In Python, return and remove the 3rd item in list T?

A

T.pop(2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

In Python, s = ‘hello’

What does the following return?

s[2:4]

A

ll

s[start:up to, but not including]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

In Python and np, how do you flip an array Dat with rows and columns?

A

Dat.T()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

In Python and np:

names = array of 7 names
data = 7 by 4 d.array

What does the following return?

data[names == “Bob”|names == ‘Will’]

A

The rows of data at the index of names that equal ‘Bob’ or ‘Will’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

In lexical resources, what is the word itself called?

A

the headword or lemma

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

In lexical resources, what is the classification as a noun, verb, etc., called?

A

The part-of-speech or lexical category

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

In lexical resources, what is the meaning referred to as?

A

Sense definition or gloss

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

In Python, tup = (4, 5, (6, 7))

Unpack tup?

A

a, b, (c, d) = tup

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

In Python, test if string S has a title capitilization?

A

S.istitle()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

In Python, what module is useful to add items into a sorted list?

A

bisect

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Assuming data is an np nd.array, how many rows & columns?

A

data.shape

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

In Python and np, how do you copy an array?

A

array.copy()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

In Python, rewrite the following as a list comprehension?

flattened = []
for tup in some_tuples:
for x in tup:
flattened.append(x)

A

flattened = [x for tup in some_tuples for x in tup]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

In Python, how do you create a list of 1 - 10?

A

range(1, 11)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

In Python, how do you create a list of 10 - 20?

A

range(10, 21)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

In Python, how do you create a list of 10, 12, 14, 16, 18, 20?

A

range(10, 21, 2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

In nltk, view a graph of Conditional Frequency Distribution called cfd?

A

cfd.plot()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

With pd, dat has columns year and state.

Create a column called myNum that equals 16 for all records?

A

dat[‘myNum’] = 16

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

With pd, dat is a list object of multiple dictionaries.

Create a data frame?

A

DataFrame(dat)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

In Python, define a feature extractor for documents that searches a document for a list of words and returns a feature set?

A

def myFunc(list_of_words, a_document):

- >doc_words = set(a_document)
- >to_return = {}
- >for words in list_of_words:
	- >->to_return['contains(%s)' % words] = words in doc_words
- >to_return
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

With pd, what are 2 ways to return a column from a DataFrame?

A

Attr: dat.name
Dict: dat[‘name’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

With pd, assign -5 to Series object dat at index ‘t’?

A

dat[‘t’] = -5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

With pd, create a series from 4, 7, 2, 1?

A

Series([4, 7, 2, 1])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Load pandas?

A

import pandas as pd

from pandas import Series, DataFrame

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Assuming this_dat is an np nd-array, what is the type?

A

this_dat.dtype

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

With pd, return just Series obj’s values?

A

obj.values

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

In pd, 2 ways to use .isnull and .notnull?

A

Either as a method of an object or a pd function applied to an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

With pd, return Series object–obj–index?

A

obj.index

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

In Python and np, return set difference of x vs. y?

A

np.setdiff1d(x, y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

In Python, view the conditions associated with a Conditional Frequency Distribution called CFD?

A

CFD.conditions()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

With pd, assign column order of ‘state’ then ‘year’ to dat DataFrame?

A

DataFrame(dat, columns = [‘state’, ‘year’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

In Python and np, return the intersection of x and y?

A

np.intersect1d(x, y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

With pd, what happens when you build a DataFrame out of a nested dictionary with 2 levels?

A

Outer dict keys become the columns and the inner keys are the rows.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

In Python and np, dat is an array, return another array of 2s and -2s depending on whether dat’s value is positive?

A

np.where(dat > 0, 2, -2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

In NLTK, return words that commonly appear around “car” and “bus” in T?

A

T.common_contexts([‘car’, ‘bus’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

In NLTK, create a plot showing where “car”, “bus”, and “stew” appear in T?

A

T.dispersion_plot([‘car’, ‘bus’, ‘stew’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

In Python and np, return unique items in x?

A

np.unique(x)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

With pd, dat is a dictionary. What does Series(dat) do?

A

Creates a Series object with dat’s keys as an index and in sorted order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

In NLTK, after creating 2 lists of words, TEXT1 and TEXT2, how do you find the unique words in TEXT1?

A

TEXT1.difference(TEXT2)
or
TEXT1 - TEXT2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

With NLTK, create a concordance with text object T?

A

T.concordance(‘myword’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

In Python, what is for loop to return the number and existence of each letter in the string variable STRING?

A

a_dict = {}
for L in ‘abcdefghijklmnopqrstuv’:
-> a_dict[L] = STRING.lower().count(L)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

What are ways to get a list of keys from a Python dictionary, dict?

A

Treat it like a list and the keys will be the list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

In Python, iterate over unique items in S?

A

for item in set(S)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

In Python, iterate over a unique set of items in S that are not in T?

A

for item in set(S).difference(T)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

In Python, iterate over a random set of items in S?

A

for item in random.shuffle(S)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

With pd, delete column State from dat?

A

del dat[‘State’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

In Python, how do you write to a file?

A
with open("file.txt", "w") as f:
-> f.write("here is some text")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

With NLTK, how do I create a stop-words object that contains a list of english stop-words?

A

nltk.corpus.stopwords.words(‘english’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

In Python and np, return union of x and y?

A

np.union1d(x, y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

In NLTK, return words that have a similar concordance with “apple” in T?

A

T.similar(“apple”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

In Python, add [4, ‘foo’, 3, ‘red’] to list T?

A

T.extend([4, ‘foo’, 3, ‘red’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

In NLTK, generally describe in code how to create a conditional frequency distribution?

A

nltk.ConditionalFreqDist(tuple of words like (condition, word))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

In Python, use code to confirm x is an integer, returning True or False?

A

isinstance(x, int)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

In Python, add ‘word’ at index 3 to list T, sliding all other values to the right?

A

T.insert(3, ‘word’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

With NLTK, tag all words in TEXT with ‘n’?

A

my_tagger = nltk.DefaultTagger(‘n’)

my_tagger.tag(TEXT)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

With NLTK, tag all words with tuples of the form (regex, “tag”) stored in PATTERNS?

A

nltk.RegexpTagger(PATTERNS)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

With NLTK, tag all words based on a lookup list stored in TAGS, while backing off to a tagger that tag “Unk” for any word not in the lookup?

A
nltk.UnigramTagger(model = TAGS, 
backoff = nltk.DefaultTagger("Unk"))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

In Python, add ‘word’ to the end of list T?

A

T.append(‘word’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

In Python and np, return boolean for items from x that are in y?

A

np.in1d(x, y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

Create a Python function for creating a measure for the lexical diversity of TEXT?

A
def lexDef(TEXT):
-> return (len(TEXT) / len(set(TEXT))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

In Python, how do you continue onto the next line outside parenthesis?

A

”"

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

In Python, return the intersection of S1 and S2?

A

S1.intersection(S2)
or
S1 & S2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

In Python, create a table of a conditional frequency distribution call CFD?

A

CFD.tabulate()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

In Python, why are some functions names prefixed by “___”?

A

They are hidden objects meant to only be used within a module and, as a result, will not be imported when the rest of a library is imported.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

In NLTK, how do you create an NLTK corpus from a set of text files?

A

from nltk import PlaintextCorpusReader

corpus = PlaintextCorpusReader(file_path, REGEX_FOR_FILENAMES)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

WordNet: What is a hypernym?

A

Words that are up the hierarchy (corvette -> car)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

WordNet: What is a hyponym?

A

Words that are down the hierarchy (car -> corvette)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

WordNet: What is a meronym?

A

Components of a word (tree is made up of branch, root, and leaves)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

WordNet: What is a holonym?

A

What a word is contained in (forest includes trees, a forest is a holonym of tree)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

WordNet: What does entail mean?

A

Specific steps in a verb (walking -> stepping)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

In Python, after importing os, how do you see your working dir?

A

os.getcwd()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

In NLTK, n-gram functions?

A

nltk. util.bigram(TEXT)
nltk. util.trigram(TEXT)
nltk. util.ngram(TEXT, n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

In Python:

def search1(subst, words):

  • > for word in words:
  • > -> if subst in word:
  • > ->-> yield word

What and why?

A

This is a generator and is usually more efficient than building a list to store.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

In regex, search for any letter from a to m?

A

[a-m]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

In regex, search for any letter in the word chasm?

A

[chasm]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

In regex search for the word chasm or bank?

A

‘chasm|bank’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

In Python, how do I slice a portion of a STRING that is after the word “START” and up to the word “END”?

A

STRING[STRING.find(‘START’):STRING.find(‘END’)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

In Python, return the union of SET1 and SET2?

A

SET1 | SET2
or
SET1.union(SET2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

In Python, test if string S is all numbers?

A

S.isdigits()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

In Python and np, create an array with 0-14?

A

np.arange(15)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

In NLTK, assuming I have a RAW string file, how do I tokenize it?

A

nltk.word_tokenize(RAW)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

With a frequency distribution (fdist), get a word’s percent frequency?

A

fdist.freq(‘word’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

With a freq. dist. (fdist), get n?

A

fdist.N()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

With a freq. dist. (fdist), get a plot?

A

fdist.plot()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

With a freq. dist. (fdist), get a cumulative plot?

A

fdist.plot(cumulative = True)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

In Python, test if string S’s last letter is “L”?

A

S.endswith(“L”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
Q

In Python, test if string S is all non-capitalized letters?

A

S.islower()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

In Python, test if string S is composed of letters and numbers?

A

S.isalnum()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

In Python, test if string S is all letters?

A

S.isalpha()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

In Python, test if string S is all capital letters?

A

S.isupper()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
111
Q

In Python and np, return items in x or y, but not both?

A

np.setxor1d(x, y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
112
Q

In regex, what is ‘a*’?

A

0 or more of ‘a’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
113
Q

In regex, what is ‘a+’?

A

1 or more of ‘a’

114
Q

In regex, what is ‘a?’?

A

0 or 1 of ‘a’

115
Q

In Python, given STRING return the location of “a” going from left to right, but return -1 if not found?

A

STRING.find(“a”)

116
Q

In Python, given STRING return the location of “a” going from right to left, but return -1 if not found?

A

STRING.rfind(“a”)

117
Q

In Python, given STRING return the location of “a” going from left to right, but return ValueError if not found?

A

STRING.index(“a”)

118
Q

In Python, given STRING return the location of “a” going from right to left, but return ValueError if not found?

A

STRING.rindex(“a”)

119
Q

In Python, given STRING, return it as all lower case?

A

STRING.lower()

120
Q

In Python, given STRING, return it as all upper case?

A

STRING.upper()

121
Q

In Python, given STRING, return it as title casing?

A

STRING.title()

122
Q

In Python, merge the elements of STRING or LIST with “-“?

A

”-“.join(STRING)

“-“.join(LIST)

123
Q

In Python, split A_SENTENCE by the spaces?

A

A_SENTENCE.split(“ “)

124
Q

In Python, split A_DOCUMENT_STRING by new lines?

A

A_DOCUMENT_STRING.splitlines()

125
Q

In Python, remove leading and trailing whitespace from STRING?

A

STRING.strip()

126
Q

In Python, replace all occurrences of the letter ‘e’ with ‘-‘ in STRING?

A

STRING.replace(“e”, “-“)

127
Q

What is an NLTK Text object?

A

A python list of each individual word and punctuation mark from a STRING or DOCUMENT.

128
Q

___ i in ITERABLE:

  • > __ ITERABLE[i] == 10:
  • > -> 1
  • > __ ITERABLE[i] == 15:
  • > -> 0
  • > __
  • > -> “Neither”
A

for i in ITERABLE:

  • > if ITERABLE[i] == 10:
  • > -> 1
  • > elif ITERABLE[i] == 15:
  • > -> 0
  • > else:
  • > -> “Neither”
129
Q

As list comprehension:

for obj in objects:

  • > if obj == 10:
  • > -> myFunc(obj)
A

[myFunc(obj) for obj in objects if obj == 10]

130
Q

In Python’s Regex: add word boundary to end of pattern “the”?

A

r”the\b”

131
Q

In Python’s Regex: pattern to find 2 or 3 digits?

A

r”\d{2,3}”

132
Q

In Python’s Regex: pattern to find 5 non-digits?

A

r”\D{5}”

133
Q

In Python’s Regex: pattern to find 0 or 1 spaces?

A

r”\s?”

134
Q

In Python’s Regex: pattern to find a non-space?

A

r”\S”

135
Q

In Python’s Regex: pattern to find a alphanumerics?

A

r”\w”

136
Q

In Python’s Regex: pattern to find anything but alphanumerics?

A

r”\W”

137
Q

In Python’s Regex: pattern to find a tab?

A

r”\t”

138
Q

In Python’s Regex: pattern to find a new line?

A

r”\n”

139
Q

Python’s “not equal”?

A

!=

140
Q

Python’s “equal to”

A

==

141
Q

Python’s “less than or equal”?

A

<=

142
Q

Python: test for x is greater than 10 but less than or equal to 15?

A

10 < x <= 15

143
Q

Sort myDict by its value?

A

from operator import itemgetter

newDict = sorted(myDict.items(), key = itemgetter(1))

144
Q

In Python, open and read the content of a TEXT.txt into STRING?

A
with open("TEXT.txt", "r") as f:
-> STRING = f.read()
145
Q

With NLTK, create a list of English words from UNIX dictionary?

A

english_vocab = set(w.lower() for w in nltk.corpus.words.words())

146
Q

Create an NLTK Text object from tokenized text?

A

nltk.Text(tokens)

147
Q

What NLTK function is a version of defaultdict with sorting and plotting methods?

A

nltk.Index()

148
Q

What is Brill tagging?

A

Transformation based learning where a model guess the tag of each word, but then fixes mistakes based on context.

Rules are of the form “retag x to y if z comes before it”

149
Q

In Python, return myDict’s keys?

A

myDict.keys()

150
Q

In Python, return myDict’s items as a list of tuples?

A

myDicts.items()

151
Q

In Python, return myDict’s values?

A

myDict.values()

152
Q

With nltk, remove HTML tags from this_object?

A

nltk.clean_html(this_object)

153
Q

In Python, test if STRING’s first letter is “A”?

A

STRING.startswith(“A”)

154
Q

With pd, add or change DATAFRAME’s name for its columns or index?

A
DATAFRAME.column.name = "NEW_NAME"
DATAFRAME.index.name = "NEW_NAME"
155
Q

With nltk, count all words in TEXT? (I believe this must be a nltk.Text object)

A

nltk.FreqDist(TEXT)

156
Q

In Python’s Regex: pattern to find “a” followed by any character but a new line?

A

r”a.”

157
Q

In Python’s Regex: pattern to find the word “the”, but not as part of any other word?

A

r”^the$”

158
Q

In Python’s Regex: pattern to anything but vowels?

A

r”[^aeiou]”

159
Q

In Python, finish this code to create NewText, wihch only includes the top 1000 most frequent words and replaces all others with “Unk”?

from collections import defaultdict
vocab = nltk.FreqDist(OldText)
v1000 = list(vocab)[:1000]

now what?

A

map = defaultdict(lamda: “Unk”)

for v in v1000:
-> map[v] = v

NewText = [map[v] for v in OldText]

160
Q

Using Python’s list comprehension, count the number of times words ending in ‘ed’, ‘ing’, or ‘es’ show up in My_Text?

A

sum([1 for w in My_Text if re.search(r”ed$|ing$|es$”, w)])

161
Q

In Python, import and start debugger on myFunc?

A

import pdb

pdb.run(“myFunc()”)

162
Q

In Python, while in debugger, execute the current line?

A

step

163
Q

In Python, while in debugger, execute through the next line?

A

next

164
Q

In Python, while in debugger, execute up to the next break point?

A

continue

165
Q

In Python, while in debugger, how do you view the value of Obj?

A

Obj

166
Q

In Python, while in debugger, how do you see the value of a function’s parameter??

A

argument name

167
Q

In Python’s debugger, how do you view or list break points?

A

break on command line or in code

168
Q

With nltk’s Text, find every instance of “a * man”, but return only *?

A

Text.findall(r”<a> (.*) “)</a>

169
Q

In Python, derive the vocab from Text?

A

set([w.lower() for w in Text if w.isalpha()])

170
Q

In Python, test if STRING contains SUBSTRING?

A

SUBSTRING in STRING

171
Q

In Python, how do I check what kind of object MY_OBJECT is?

A

type(MY_OBJECT)

172
Q

In Python, return the actual result of 5 divided by 2?

A

5 / 2

173
Q

In Python, return the integer result of 5 divided by 2?

A

5 // 2

174
Q

In Python, return the remainder from 5 divided by 2?

A

5 % 2

175
Q

In Python, what is another way to do the following:

a = a + 3?

A

a += 3

176
Q

In Python, return the remainder and integer result of 5 divided by 2?

A

divmod(5, 2)

177
Q

In Python, what does int(98.7) return?

A

98 because it just lops off everything after the decimal

178
Q

In Python:

bottles = 99
base = 'current inventory: '

Add bottles to base?

A

base += str(bottles)

179
Q

In Python:

a = Duck.
b = a
c = Grey Duck!

Result of a + b + c vs. print(a, b, c)?

A

a + b + c = Duck.Duck.Grey Duck!

print(a, b, c) = Duck. Duck. Grey Duck!

180
Q

In Python, what happens and what are solutions?

name = 'Henry'
name[0] = 'P'
A

TypeError because strings are immutable.

Must use name.replace(“H”, “P”) or “P” + name[1:]

181
Q

In Python, how many times does WORD appear in LONG_STRING?

A

LONG_STRING.count(WORD)

182
Q

In Python, return MY_LIST in reverse?

A

MY_LIST[::-1]

183
Q

In Python, another way to do:

MY_LIST.extend(YOUR_LIST)

A

MY_LIST += YOUR_LIST

184
Q

In Python, another way to do:

MY_LIST += YOUR_LIST

A

MY_LIST.extend(YOUR_LIST)

185
Q

In Python, what is the difference between MY_LIST.extend(YOUR_LIST) and MY_LIST.append(YOUR_LIST)?

A

MY_LIST.extend(YOUR_LIST) returns a single list

MY_LIST.append(YOUR_LIST) makes MY_LIST[:-1] = YOUR_LIST (a list within a list)

186
Q

In Python, get rid of ‘item_a’ in MY_LIST?

A

MY_LIST.remove(‘item_a’)

187
Q

In Python, return and then get rid of ‘item_a’ in MY_LIST?

A

MY_LIST.pop(‘item_a’)

188
Q

In Python, return the index of ‘item_a’ in MY_LIST?

A

MY_LIST.index(‘item_a’)

189
Q

In Python, how many times does ‘item_a’ appear in MY_LIST?

A

MY_LIST.count(‘item_a’)

190
Q

In Python, what is the difference between:

MY_LIST.sort()
sorted(MY_LIST)

A

MY_LIST.sort() changes MY_LIST (and does not return the result)

sorted(MY_LIST) returns a sorted copy of MY_LIST

191
Q

In Python:

a = [1, 2, 3]
b = a
a[0] = 5

What does b return?

A

[5, 2, 3]

192
Q

In Python, create a new version of MY_LIST in NEW_LIST? (3 ways)

A
NEW_LIST = MY_LIST.copy()
or
NEW_LIST = list(MY_LIST)
or
NEW_LIST = MY_LIST[:]
193
Q

In Python, delete all keys and values from a MY_DICTIONARY? (2 ways)

A

MY_DICTIONARY.clear()
or
MY_DICTIONARY = {}

194
Q

In Python, MY_DICTIONARY does not have THIS_KEY.

What is the difference?

MY_DICTIONARY.get(“THIS_KEY”, “Nope”)
MY_DICTIONARY[“THIS_KEY”]

A

MY_DICTIONARY.get(“THIS_KEY”, “Nope”)
returns “Nope”

MY_DICTIONARY[“THIS_KEY”]
Returns an error

195
Q

In Python 3, what is the difference?

MY_DICT.keys()

list(MY_DICT.keys())

A

MY_DICT.keys()
returns MY_DICT.dict_keys(), which is an iterable view of the keys

list(MY_DICT.keys())
returns a converted version of the iterable view, which is a list

196
Q

In Python, create a new version of MY_DICT that keeps the dictionary’s values and keys?

A

MY_DICT.copy()

197
Q

In python, what does this return?

bool( { ‘a’, ‘b’, ‘c’ } & { ‘d’, ‘e’, ‘f’ } )

A

False because the two sets have nothing in common

198
Q

In python, what does this return?

bool( [ ‘a’, ‘b’, ‘c’ ] & { ‘d’, ‘e’, ‘f’ } )

A

An error because the first component is a list

199
Q

In Python, what does this return?

{‘a’, ‘b’, ‘c’} ^ {‘d’, ‘e’, ‘a’}

A

{‘b’, ‘c’, ‘d’, ‘e’}

200
Q

In Python, what is another version of this?

SET1.issubset(SET2)

A

SET1 <= SET2

201
Q

In Python, what is another version of this?

SET1.issuperset(SET2)

A

SET1 >= SET2

202
Q

In Python, make a tuple of lists out of LIST1, LIST2, LIST3?

A

tup_of_lists = LIST1, LIST2, LIST3

203
Q

In Python, count = 1, create a while loop that adds to count until it is equal to 50?

A

while count < 50:

-> count += 1

204
Q

In Python, create an infinite loop that capitalizes the users input and stops only when the user enters ‘q’?

A

while True:

  • > user_input = input(‘Enter Here: “)
  • > if user_input == ‘a’:
  • > -> break
  • > print(user_input.upper())
205
Q

In Python, how do you make a loop start the next iteration without completed the remaining code within the current loop?

A

continue

206
Q

In Python, when will this end?

for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts):
-> print(day, fruit, drink, dessert)

A

When the shortest sequence is done

207
Q

Describe Python’s list comprehension?

A

[ expression for item in iterable if condition ]

208
Q

Describe Python’s dictionary comprehension?

A

{ key_expression : value_expression for item in iterable if condition }

209
Q

Describe Python’s set comprehension?

A

{ expression for item in iterable }

210
Q

In Python, what is this?

expression for item in iterable if condition

A

It is a generator comprehension

211
Q

In Python, create a function that repeats an argument with a space between it?

A
def echo(arg):
-> return arg + " " + arg
212
Q

Change this Python function so that it can take any number of arguments:

def print_this(VARIABLE):
-> print(VARIABLE)
A
def print_this(*args):
-> print( args )
213
Q

When defining a function in Python, how do you gather all keyword arguments into a dictionary?

A

**kwargs

kwargs is the name of the dictionary to use in the function, but technically ‘ ** ‘ is what tells Python to gather the keyword arguments into a dictionary, which–by convention–is called kwargs

214
Q

In Python, where do you put a function’s documentation?

A

As a docstring at the start of the function’s body as a comment

215
Q

In Python, print print’s docstring?

A

print(print.__doc__)

216
Q

In Python, add an error handler that simply prints MSG:

def add_this(first, second):
-> return first + second
A

def add_this(first, second):

  • > try:
  • > -> return first + second
  • > except:
  • > -> print(MSG)
217
Q

In Python, test.py prints out “Program arguments: [file_name, and other arguments]”. What does test.py say?

A

import sys

print(“Program arguments: “, sys.argv)

218
Q

In Python, return a random item from THIS_LIST

A

random.choice(THIS_LIST)

219
Q

Where does Python look for modules?

A

Based on the items listed in sys.path

220
Q

What function is helpful for printing an index value along with each item in LIST?

A

enumerate()

221
Q

How do you make Python treat MY_DIR as a Python package?

A

Make sure there is a file called __init__.py, which can be empty.

222
Q

In Python, return my_dict[‘key’] by assigning 12 if ‘key’ does not already exist and otherwise just returns its current value?

A

my_dict.setdefault( ‘key’, 12 )

223
Q

In Python, MY_LIST is a list of objects, which sometimes repeat. How many of each item are in MY_LIST?

A

from collections import Counter

Counter(MY_LIST)

224
Q

In Python, what is the most popular item or items?

from collections import Counter

item_counter = Counter(item)

A

item_counter.most_common(1)–most popular item

item_counter.most_common()–all items, in sorted order

225
Q

In Python, what does this check?

word == word[::-1]

A

Is word a palindrome?

226
Q

In Python, given a list, what object and methods are useful to pull items from either side?

A

from collections import deque

  • pop
  • popleft
227
Q

In Python, given 4 lists, what function is useful to go through items, 1 at a time, across all 4 lists?

A

from itertools import chain

228
Q

In Python, what function is useful for continuously iterating through LIST?

A

from itertools import cycle

229
Q

In Python, what function is useful for cumulative functions, such as sum?

A

from itertools import accumulate

230
Q

In Python, how do you create an easier to read print out?

A

from pprint import pprint

231
Q

In Python, create a class for Person that stores a name?

A

class Person():

  • > def __init__(self, name):
  • > -> self.name = name
232
Q

In OOP, what are names for an original class?

A

superclass, parent class, base class

233
Q

In OOP, what names for classes that inherit something from a an original class?

A

subclass, child class, derived class

234
Q

In Python, create a Child class that inherits everything from a Parent class and does nothing additional?

A
class Child(Parent):
-> pass
235
Q

In Python, create a class for Doctor that stores a name and has method to greet a patient by name?

A

class Doctor():

  • > def __init__(self, name):
  • > -> self.name = name
  • > def greeting(self, patient):
  • > -> self.greeting = print(“Hello”, patient, “I’m Doctor”, self.name)
236
Q

In Python, why use super()?

A

If you are creating a subclass with a new __init__ definition, but still want to inherit items from the parent class

237
Q

In Python,

class Circle():

  • > def __init__(self, radius):
  • > -> self.radius = radius
  • > @property
  • > def diameter(self):
  • > -> return 2 * self.radius

test = Circle(30)

What happens when you run:

test.diameter = 15

A

An exception because diameter is a attribute that can’t be set directly. This is identified by the @property tag, which would otherwise make diameter a method rather than an attribute.

238
Q

What is a class method and how is it distinguished?

A

It is a method that affects the class as a whole, as opposed to an instance method, which affects only a particular instance of the class. It is distinguished with the @classmethod decorator tag.

239
Q

In Python, how do you identify how to print a class?

A

Use the __str__ magic method to define how you print a class when print(class) is called.

240
Q

In Python, create a named tuple called ‘document’ that has attr1, attr2, and attr3 as its composition?

Then use it for item1, item2, item3.

A

from collections import namedtuple

the_tuple = namedtuple(‘document’, ‘attr1 attr2 attr3’)

the_tuple(item1, item2, item3)

241
Q

Using old style strings in Python, create a string that says the following, but “Hunter” and “1984” are variables:

“My name is Hunter and I was born in 1984”

A

“My name is %s and I was born in %s” % (name, year)

242
Q

Using new style strings in Python, create a string that says the following, but “Hunter” and “1984” are variables:

“My name is Hunter and I was born in 1984”

A

“My name is {} and I was born in {}”.format(name, year)

243
Q

In Python regular expressions, what is the difference between the methods and functions?

A

The methods require calling re.compile(pattern) first, but then the search will be sped up. If not necessary, re.functionname(pattern, object) is a reasonable alternate.

244
Q

In Python, return the first match of a regular expression PATTERN within STRING?

A

CP = re.compile(PATTERN)
CP.search(STRING)

OR

re.search(PATTERN, STRING)

245
Q

In Python, return of all non-overlapping matches to regular expression PATTERN within STRING?

A

CP = re.compile(PATTERN)
CP.findall(STRING)

OR

re.findall(PATTERN, STRING)

246
Q

In Python, return a list made from a STRING that was split at a regular expression PATTERN.

A

CP = re.compile(PATTERN)
CP.split(STRING)

OR

re.split(PATTERN, STRING)

247
Q

In Python, replace all matches to a regular expression PATTERN contained within STRING using REPLACEMENT?

A

re.sub(PATTERN, REPLACEMENT, STRING)

248
Q

In Python, check to see if the STRING starts with the regular expression PATTERN?

A

CP = re.compile(PATTERN)
CP.match(STRING)

OR

re.match(PATTERN, STRING)

249
Q

Create a regex that finds pat1 if is not followed by pat2?

A

pat1(!=pat2)

250
Q

Create a regex that finds pat1 if it is preceded by pat2?

A

(?<=pat2)pat1

251
Q

Create a regex that finds pat1 if it is not preceded by pat2?

A

(?<1pat2)pat1

252
Q

Describe the pattern for use in re.search or re.match that allows you to name groups?

A

(?P< name > pattern)

253
Q

Create a regex that finds pat1 if is followed by pat2?

A

pat1(?=pat2)

254
Q

Read file.txt in one line at a time, but create a single string called the_text?

A

the_text = “”
with open(“file.txt”, “r”) as f:
-> for line in f:
-> -> the_text += line

255
Q

Read in file.csv as a list (columns) of lists (rows)?

A
import csv
with open("file", "r") as f:
-> cin = csv.reader(f)
-> stuff = [row for row in cin]
256
Q

What does this do?

import csv

with open(“villians’, ‘r’) as fin:

  • > cin = csv.DictReader(fin, fieldnames = [‘first’, ‘last’])
  • > villains = [row for row in cin]

print(villains ]

A

It prints villains, which is a list of dictionaries each have a key for ‘first’ and for ‘last’

257
Q

What is the simplest way to parse XML in Python?

A

Using xml.etree.ElementTree

258
Q

Given a string JSON–in JSON format–read it into a Python dictionary?

A

import json

str_dict= json.loads(JSON)

259
Q

Verify a directory or a file exist?

A

import os

os.path.exists(directory or file)

260
Q

Verify myfile is an existing file in your working dir?

A

import os

os.path.isfile(myfile)

261
Q

Verify mydir is an existing directory?

A

os.path.isdir(mydir)

262
Q

Is myfilename an absolute path?

A

os.path.isabs(myfilename)

263
Q

Copy myfile.txt and call it newtext.txt?

A

import shutil

shutil.copy(‘myfile.txt’, ‘newtext.txt’)

264
Q

Rename myfile.txt newtext.txt?

A

import os

os.rename(‘myfile.txt’, ‘newtext.txt’)

265
Q

Get the full path name for myfile.txt, which is in your current working directory?

A

os.path.abspath(‘myfile.txt’)

266
Q

Delete myfile.txt?

A

os.remove(‘myfile.txt’)

267
Q

Create the directory, mynewdir?

A

os.mkdir(‘mynewdir’)

268
Q

Remove the directory, mynewdir?

A

os.rmdir(‘mynewdir’)

269
Q

List the items in mynewdir, which is within the current working directory?

A

os.listdir(‘mynewdir’)

270
Q

Switch to mynewdir, which is within the current working directory?

A

os.chdir(‘mynewdir’)

271
Q

Find all the files within the current working directory that start with ‘m’?

A

import glob

glob.glob(“m*”)

272
Q

What module and object deals with years, months, and days?

A

datetime.date

273
Q

What module and object deals with hours, minutes, seconds, and fractions of a second?

A

datetime.time

274
Q

What module and object deals with years, months, days, hours, minutes, seconds, and fractions of a second

A

datetime.datetime

275
Q

What module and object deals with date or time intervals?

A

datetime.timedelta

276
Q

How does the time module deal with time?

A

As seconds from January 1, 1970.

277
Q

Convert the time object, mytime, to a string?

A

time.ctime(mytime)

278
Q

What method of datetime, date, or time objects, or function from the time module is useful for converting dates and times to strings?

A

strftime()

279
Q

What method is useful for converting a string to a time object?

A

time.strptime()

280
Q

Create a switch to return VALUE based on POSSIBILITIES?

A

choices = dict(zip(POSSIBILITES, VALUE))

choices.get(a_possibility, “Default for key error”)