-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlecat.py
203 lines (176 loc) · 5.76 KB
/
lecat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import pandas as pd
import numpy as np
def parse_lexicon(lexicon):
""" Reshape lexicon from wide to long
Parameters
----------
lexicon : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: Type, dtype: float64
Name: Category, dtype: float64
Name: Query, dtype: float64
Name: Query1, dtype: object
Name: Queryx, dtype: object
Search queries, types and categories
Returns
----------
parsed_lexicon : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: Type, dtype: object
Name: Category, dtype: object
Name: Query, dtype: object
Long form lexicon
"""
# preallocate our parsed dataframe
parsed_lexicon = pd.DataFrame(columns = ['Type', 'Category', 'Query'])
# iterate over each row in lexicon
for index, row in lexicon.iterrows():
# extract columns
this_type = row['Type']
this_category = row['Category']
these_queries = row[lexicon.keys().str.startswith('Query')]
for query in these_queries:
if pd.isna(query):
continue
# append our collected data
parsed_lexicon = parsed_lexicon.append(
{'Type':this_type, 'Category':this_category, 'Query':query},
ignore_index=True)
return(parsed_lexicon)
def run_search(strings, query, this_type, this_category, column, regex = '\\bquery\\b'):
""" Search for query in strings
Parameters
----------
strings : pandas.Series
Series of strings to search.
query : str
Term to seach for.
this_type : str
Query type.
this_category : str
Query category.
regex : str
Query search regular expression.
Returns
----------
result : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: [query], dtype: int64
Counts of query in string
"""
# correctly add backslash to special characters
query = query.replace("([{\\[()|?$^*+.\\\\])", "\\$1")
regex = regex.replace('query', query)
counts = strings.str.count(regex)
# put counts into dataframe
result = pd.DataFrame({query: counts})
result = result.set_index(strings)
return(result)
def run_lecat_analysis(parsed_lexicon, corpus, regex_expression, column):
""" Run search against all lexicon entries
Parameters
----------
parsed_lexicon : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: Type, dtype: float64
Name: Category, dtype: float64
Name: Query, dtype: float64
Long form lexicon from parse_lexicon.
corpus : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: [column], dtype: object
DataFrame with at least 1 column with column name matching column parameter.
regular_expression : str
Regular expression for search.
column : str
Column name to search for. Must be column name in corpus.
Returns
----------
result : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: [query_1], dtype: int64
Name: [query_2], dtype: int64
Name: [query_n], dtype: int64
"""
# preallocate result dataframe
result = pd.DataFrame(np.nan, index = corpus.description, columns = parsed_lexicon.Query)
# run search for each query
for index, row in parsed_lexicon.iterrows():
# get features
this_query = row['Query']
these_strings = corpus[column]
this_type = row['Type']
this_category = row['Category']
# search
result[this_query] = run_search(these_strings, this_query, this_type, this_category, column, regex_expression)
return(result)
def create_unique_total_diagnostics(parsed_lexicon, lecat_result):
"""
Count the total occurences [total] and the number of corpus elements
containing each query [unique].
Parameters
----------
parsed_lexicon : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: Type, dtype: float64
Name: Category, dtype: float64
Name: Query, dtype: float64
Long form lexicon from parse_lexicon.
lecat_result : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: [query_1], dtype: int64
Name: [query_2], dtype: int64
Name: [query_n], dtype: int64
Output from run_lecat_analysis
Returns
----------
result : pandas.DataFrame
Index:
RangeIndex
Columns:
Name: Type, dtype: float64
Name: Category, dtype: float64
Name: Query, dtype: float64
"""
totals = []
uniques = []
Types = []
Categories = []
Queries = []
for query in lecat_result:
# tally up counts
n_total = sum(lecat_result[query])
n_unique = lecat_result[query].astype(bool).sum(axis=0)
# TODO: fix cases where multiple of same query
Type = parsed_lexicon.Type[parsed_lexicon.Query == query].values[0]
Category = parsed_lexicon.Category[parsed_lexicon.Query == query].values[0]
# add counts to lists
totals.append(n_total)
uniques.append(n_unique)
Types.append(Type)
Categories.append(Category)
Queries.append(query)
# put lists into a pretty dataframe
data = {'Query': Queries,
'Type': Types,
'Category': Categories,
'unique': uniques,
'total': totals}
result = pd.DataFrame(data)
return(result)