Download oe_dictionary.py from Nerthus-Project/Old_English_Dictionary_Interface: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/Nerthus-Project/Old_English_Dictionary_Interface/resolve/main/oe_dictionary.py
- Command line
-
hf download hf://datasets/Nerthus-Project/Old_English_Dictionary_Interface/oe_dictionary.py
-
curl -L -o oe_dictionary.py https://huggingface.co/datasets/Nerthus-Project/Old_English_Dictionary_Interface/resolve/main/oe_dictionary.py
11.1 kB
| import pandas as pd | |
| import re | |
| from pathlib import Path | |
| from typing import List, Dict, Optional, Union | |
| class OldEnglishDictionary: | |
| """A class to query the aligned Old English Dictionary dataset.""" | |
| def __init__(self, data_path: str = "data/unified_index.tab"): | |
| """Initialize the dictionary with the unified index. | |
| Args: | |
| data_path: Path to the unified_index.tab file | |
| """ | |
| self.data_path = Path(data_path) | |
| self.df = pd.read_csv(self.data_path, sep='\t') | |
| # Fill NaN values with empty strings for easier processing | |
| self.df = self.df.fillna('') | |
| # Create lowercase versions of key columns for case-insensitive search | |
| self.df['canonical_key_lower'] = self.df['canonical_key'].str.lower() | |
| self.df['normalised_form_lower'] = self.df['normalised_form'].str.lower() | |
| # Dictionary sources | |
| self.sources = ['BT', 'CH', 'Sweet', 'DOE', 'ParCorOE'] | |
| # Count total entries | |
| self.total_entries = len(self.df) | |
| print(f"Loaded {self.total_entries} aligned entries from {self.data_path}") | |
| def search(self, query: str, | |
| mode: str = 'canonical', | |
| exact: bool = False, | |
| pos: Optional[str] = None, | |
| source: Optional[str] = None) -> pd.DataFrame: | |
| """Search for entries matching the query. | |
| Args: | |
| query: The search term | |
| mode: Search mode ('canonical', 'normalised', 'headword') | |
| exact: If True, match the entire term; if False, use substring matching | |
| pos: Filter by part of speech | |
| source: Filter by dictionary source | |
| Returns: | |
| DataFrame with matching entries | |
| """ | |
| query = query.lower() | |
| # Base query logic | |
| if mode == 'canonical': | |
| if exact: | |
| results = self.df[self.df['canonical_key_lower'] == query] | |
| else: | |
| results = self.df[self.df['canonical_key_lower'].str.contains(query, regex=False)] | |
| elif mode == 'normalised': | |
| if exact: | |
| results = self.df[self.df['normalised_form_lower'] == query] | |
| else: | |
| results = self.df[self.df['normalised_form_lower'].str.contains(query, regex=False)] | |
| elif mode == 'headword': | |
| # Search across all dictionary headword columns | |
| mask = pd.Series(False, index=self.df.index) | |
| for source in self.sources: | |
| col = f"{source}_headword" | |
| if col in self.df.columns: | |
| if exact: | |
| mask |= (self.df[col].str.lower() == query) | |
| else: | |
| mask |= (self.df[col].str.lower().str.contains(query, regex=False, na=False)) | |
| results = self.df[mask] | |
| else: | |
| raise ValueError(f"Invalid search mode: {mode}. Use 'canonical', 'normalised', or 'headword'.") | |
| # Apply filters | |
| if pos: | |
| results = results[results['POS'].str.lower() == pos.lower()] | |
| if source: | |
| col = f"{source}_headword" | |
| if col in self.df.columns: | |
| results = results[results[col] != ''] | |
| else: | |
| raise ValueError(f"Invalid source: {source}. Use one of {self.sources}") | |
| return results | |
| def display_entry(self, entry: pd.Series) -> None: | |
| """Display a single dictionary entry in a readable format. | |
| Args: | |
| entry: A single row from the dataframe | |
| """ | |
| print("\n" + "=" * 80) | |
| print(f"CANONICAL KEY: {entry['canonical_key']}") | |
| print(f"NORMALIZED FORM: {entry['normalised_form']}") | |
| print(f"MATCH TYPE: {entry['match_type']}") | |
| if entry['POS']: | |
| print(f"PART OF SPEECH: {entry['POS']}") | |
| if entry['Gloss']: | |
| print(f"GLOSS: {entry['Gloss']}") | |
| print("-" * 80) | |
| print("DICTIONARY HEADWORDS:") | |
| for source in self.sources: | |
| col = f"{source}_headword" | |
| if col in entry and entry[col]: | |
| print(f" {source}: {entry[col]}") | |
| print("=" * 80) | |
| def display_results(self, results: pd.DataFrame, limit: int = 10) -> None: | |
| """Display search results in a readable format. | |
| Args: | |
| results: DataFrame containing search results | |
| limit: Maximum number of results to display | |
| """ | |
| num_results = len(results) | |
| if num_results == 0: | |
| print("No matching entries found.") | |
| return | |
| print(f"\nFound {num_results} matching entries.") | |
| if num_results > limit: | |
| print(f"Displaying first {limit} results.") | |
| results = results.head(limit) | |
| for _, entry in results.iterrows(): | |
| self.display_entry(entry) | |
| def find_similar(self, query: str, method: str = 'sound') -> pd.DataFrame: | |
| """Find entries similar to the query using various similarity methods. | |
| Args: | |
| query: The search term | |
| method: The similarity method ('sound', 'edit', 'prefix') | |
| Returns: | |
| DataFrame with similar entries | |
| """ | |
| query = query.lower() | |
| if method == 'sound': | |
| # Apply Ellis vocalic transformations similar to those used in alignment | |
| variations = self._generate_ellis_variations(query) | |
| mask = pd.Series(False, index=self.df.index) | |
| for variation in variations: | |
| mask |= (self.df['canonical_key_lower'] == variation) | |
| return self.df[mask] | |
| elif method == 'edit': | |
| # Crude edit distance approximation - finding entries | |
| # that share at least half their characters with the query | |
| query_set = set(query) | |
| results = [] | |
| for idx, row in self.df.iterrows(): | |
| canonical = row['canonical_key_lower'] | |
| # Skip very short terms or terms with big length difference | |
| if len(canonical) < 3 or abs(len(canonical) - len(query)) > 3: | |
| continue | |
| canonical_set = set(canonical) | |
| intersection = len(query_set.intersection(canonical_set)) | |
| union = len(query_set.union(canonical_set)) | |
| # Jaccard similarity threshold | |
| if intersection / union > 0.6: | |
| results.append(idx) | |
| return self.df.loc[results] | |
| elif method == 'prefix': | |
| # Find entries that start with the query | |
| return self.df[self.df['canonical_key_lower'].str.startswith(query)] | |
| else: | |
| raise ValueError(f"Invalid method: {method}. Use 'sound', 'edit', or 'prefix'.") | |
| def _generate_ellis_variations(self, word: str) -> List[str]: | |
| """Generate variations based on Ellis vocalic correspondences. | |
| Args: | |
| word: The input word | |
| Returns: | |
| List of phonologically plausible variations | |
| """ | |
| variations = [word] | |
| # Ellis vocalic correspondences | |
| transformations = [ | |
| (r'ie', r'y'), # fierd/fyrd | |
| (r'y', r'ie'), # fyrd/fierd | |
| (r'ie', r'i'), # diere/dire | |
| (r'i', r'ie'), # diren/dieren | |
| (r'io', r'eo'), # bion/beon | |
| (r'eo', r'io'), # beorht/biorht | |
| (r'on', r'an'), # monig/manig | |
| (r'an', r'on'), # manig/monig | |
| (r'om', r'am'), # from/fram | |
| (r'am', r'om'), # fram/from | |
| (r'rg', r'rh'), # burg/burh | |
| (r'rh', r'rg'), # burh/burg | |
| (r'ea', r'a'), # eald/ald | |
| (r'a', r'ea'), # ald/eald | |
| (r'eo', r'e') # eofot/efot | |
| ] | |
| for pattern, replacement in transformations: | |
| if pattern in word: | |
| variations.append(word.replace(pattern, replacement)) | |
| return variations | |
| def get_statistics(self) -> Dict[str, Union[int, float]]: | |
| """Get statistics about the dictionary dataset. | |
| Returns: | |
| Dictionary with statistics | |
| """ | |
| stats = { | |
| "total_entries": self.total_entries, | |
| "multi_source_entries": len(self.df[self.df['match_type'] != 'single']), | |
| "exact_matches": len(self.df[self.df['match_type'] == 'exact']), | |
| "ellis_matches": len(self.df[self.df['match_type'] == 'ellis_vocalic']), | |
| "single_source": len(self.df[self.df['match_type'] == 'single']) | |
| } | |
| # Add source-specific counts | |
| for source in self.sources: | |
| col = f"{source}_headword" | |
| if col in self.df.columns: | |
| stats[f"{source}_entries"] = len(self.df[self.df[col] != '']) | |
| # Add POS distribution | |
| pos_counts = self.df['POS'].value_counts().to_dict() | |
| stats["pos_distribution"] = pos_counts | |
| return stats | |
| # Example usage | |
| if __name__ == "__main__": | |
| oe_dict = OldEnglishDictionary() | |
| # Simple demo of the search functionality | |
| print("\n=== SEARCH DEMONSTRATION ===") | |
| # Search by canonical key | |
| print("\nSearching for entries with canonical key containing 'abelgan'...") | |
| results = oe_dict.search("abelgan", mode="canonical") | |
| oe_dict.display_results(results) | |
| # Search by normalized form | |
| print("\nSearching for entries with normalized form containing 'ābēodan'...") | |
| results = oe_dict.search("ābēodan", mode="normalised", exact=True) | |
| oe_dict.display_results(results) | |
| # Search by headword across all dictionaries | |
| print("\nSearching for entries where any dictionary has headword containing 'cyning'...") | |
| results = oe_dict.search("cyning", mode="headword") | |
| oe_dict.display_results(results, limit=5) | |
| # Filter by part of speech | |
| print("\nSearching for noun entries with canonical key containing 'helm'...") | |
| results = oe_dict.search("helm", mode="canonical", pos="N") | |
| oe_dict.display_results(results, limit=5) | |
| # Find similar words | |
| print("\nFinding entries similar to 'beon' using sound correspondences...") | |
| results = oe_dict.find_similar("beon", method="sound") | |
| oe_dict.display_results(results) | |
| # Show dictionary statistics | |
| stats = oe_dict.get_statistics() | |
| print("\n=== DICTIONARY STATISTICS ===") | |
| for key, value in stats.items(): | |
| if key != "pos_distribution": | |
| print(f"{key}: {value}") | |
| print("\nPart of Speech Distribution:") | |
| for pos, count in stats["pos_distribution"].items(): | |
| if pos: # Skip empty POS | |
| print(f" {pos}: {count}") |