| 253 | #--- TAXONOMY -------------------------------------------------------------------------------------- |
| 254 | |
| 255 | class Taxonomy(dict): |
| 256 | |
| 257 | def __init__(self): |
| 258 | """ Hierarchical tree of words classified by semantic type. |
| 259 | For example: "rose" and "daffodil" can be classified as "flower": |
| 260 | taxonomy.append("rose", type="flower") |
| 261 | taxonomy.append("daffodil", type="flower") |
| 262 | print taxonomy.children("flower") |
| 263 | Taxonomy terms can be used in a Pattern: |
| 264 | FLOWER will match "flower" as well as "rose" and "daffodil". |
| 265 | The taxonomy is case insensitive by default. |
| 266 | """ |
| 267 | self.case_sensitive = False |
| 268 | self._values = {} |
| 269 | self.classifiers = [] |
| 270 | |
| 271 | def _normalize(self, term): |
| 272 | try: |
| 273 | return not self.case_sensitive and term.lower() or term |
| 274 | except: # Not a string. |
| 275 | return term |
| 276 | |
| 277 | def __contains__(self, term): |
| 278 | # Check if the term is in the dictionary. |
| 279 | # If the term is not in the dictionary, check the classifiers. |
| 280 | term = self._normalize(term) |
| 281 | if dict.__contains__(self, term): |
| 282 | return True |
| 283 | for classifier in self.classifiers: |
| 284 | if classifier.parents(term) \ |
| 285 | or classifier.children(term): |
| 286 | return True |
| 287 | return False |
| 288 | |
| 289 | def append(self, term, type=None, value=None): |
| 290 | """ Appends the given term to the taxonomy and tags it as the given type. |
| 291 | Optionally, a disambiguation value can be supplied. |
| 292 | For example: taxonomy.append("many", "quantity", "50-200") |
| 293 | """ |
| 294 | term = self._normalize(term) |
| 295 | type = self._normalize(type) |
| 296 | self.setdefault(term, (odict(), odict()))[0].push((type, True)) |
| 297 | self.setdefault(type, (odict(), odict()))[1].push((term, True)) |
| 298 | self._values[term] = value |
| 299 | |
| 300 | def classify(self, term, **kwargs): |
| 301 | """ Returns the (most recently added) semantic type for the given term ("many" => "quantity"). |
| 302 | If the term is not in the dictionary, try Taxonomy.classifiers. |
| 303 | """ |
| 304 | term = self._normalize(term) |
| 305 | if dict.__contains__(self, term): |
| 306 | return self[term][0].keys()[-1] |
| 307 | # If the term is not in the dictionary, check the classifiers. |
| 308 | # Returns the first term in the list returned by a classifier. |
| 309 | for classifier in self.classifiers: |
| 310 | # **kwargs are useful if the classifier requests extra information, |
| 311 | # for example the part-of-speech tag. |
| 312 | v = classifier.parents(term, **kwargs) |
no outgoing calls
no test coverage detected
searching dependent graphs…