Created
March 17, 2025 17:42
-
-
Save MNoichl/085ca109e307b0eeed211a5026398ef3 to your computer and use it in GitHub Desktop.
OpenAlex-url to pyalex-query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| from urllib.parse import urlparse, parse_qs | |
| from pyalex import Works | |
| import pandas as pd | |
| def openalex_url_to_pyalex_query(url): | |
| """ | |
| Convert an OpenAlex search URL to a pyalex query. | |
| Args: | |
| url (str): The OpenAlex search URL. | |
| Returns: | |
| tuple: (Works object, dict of parameters) | |
| """ | |
| parsed_url = urlparse(url) | |
| query_params = parse_qs(parsed_url.query) | |
| # Initialize the Works object | |
| query = Works() | |
| # Handle filters | |
| if 'filter' in query_params: | |
| filters = query_params['filter'][0].split(',') | |
| for f in filters: | |
| if ':' in f: | |
| key, value = f.split(':', 1) | |
| if key == 'default.search': | |
| query = query.search(value) | |
| else: | |
| query = query.filter(**{key: value}) | |
| # Handle sort - Fixed to properly handle field:direction format | |
| if 'sort' in query_params: | |
| sort_params = query_params['sort'][0].split(',') | |
| for s in sort_params: | |
| if ':' in s: # Handle field:direction format | |
| field, direction = s.split(':') | |
| query = query.sort(**{field: direction}) | |
| elif s.startswith('-'): # Handle -field format | |
| query = query.sort(**{s[1:]: 'desc'}) | |
| else: # Handle field format | |
| query = query.sort(**{s: 'asc'}) | |
| # Handle other parameters | |
| params = {} | |
| for key in ['page', 'per-page', 'sample', 'seed']: | |
| if key in query_params: | |
| params[key] = query_params[key][0] | |
| return query, params | |
| query, params = openalex_url_to_pyalex_query("https://openalex.org/works?page=1&filter=title_and_abstract.search%3Ahopfield%20model") | |
| query_length = query.count() | |
| print(query_length) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment