Returns a list of (percentage, term)-tuples for the given list of terms. Sorts the terms in the list according to search result count. When a context is defined, sorts according to relevancy to the context, e.g.: sort(terms=["black", "green", "red"], context="Darth Vader") =
(terms=[], context="", service=GOOGLE, license=None, strict=True, reverse=False, **kwargs)
| 2557 | } |
| 2558 | |
| 2559 | def sort(terms=[], context="", service=GOOGLE, license=None, strict=True, reverse=False, **kwargs): |
| 2560 | """ Returns a list of (percentage, term)-tuples for the given list of terms. |
| 2561 | Sorts the terms in the list according to search result count. |
| 2562 | When a context is defined, sorts according to relevancy to the context, e.g.: |
| 2563 | sort(terms=["black", "green", "red"], context="Darth Vader") => |
| 2564 | yields "black" as the best candidate, because "black Darth Vader" is more common in search results. |
| 2565 | - terms : list of search terms, |
| 2566 | - context : term used for sorting, |
| 2567 | - service : web service name (GOOGLE, YAHOO, BING), |
| 2568 | - license : web service license id, |
| 2569 | - strict : when True the query constructed from term + context is wrapped in quotes. |
| 2570 | """ |
| 2571 | service = SERVICES.get(service, SearchEngine)(license, language=kwargs.pop("language", None)) |
| 2572 | R = [] |
| 2573 | for word in terms: |
| 2574 | q = reverse and context+" "+word or word+" "+context |
| 2575 | q.strip() |
| 2576 | q = strict and "\"%s\"" % q or q |
| 2577 | r = service.search(q, count=1, **kwargs) |
| 2578 | R.append(r) |
| 2579 | s = float(sum([r.total or 1 for r in R])) or 1.0 |
| 2580 | R = [((r.total or 1)/s, r.query) for r in R] |
| 2581 | R = sorted(R, reverse=True) |
| 2582 | return R |
| 2583 | |
| 2584 | #print sort(["black", "happy"], "darth vader", GOOGLE) |
| 2585 |