| 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') |
| |
| |
| self.df = self.df.fillna('') |
| |
| |
| self.df['canonical_key_lower'] = self.df['canonical_key'].str.lower() |
| self.df['normalised_form_lower'] = self.df['normalised_form'].str.lower() |
| |
| |
| self.sources = ['BT', 'CH', 'Sweet', 'DOE', 'ParCorOE'] |
| |
| |
| 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() |
| |
| |
| 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': |
| |
| 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'.") |
| |
| |
| 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': |
| |
| 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': |
| |
| |
| query_set = set(query) |
| results = [] |
| |
| for idx, row in self.df.iterrows(): |
| canonical = row['canonical_key_lower'] |
| |
| 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)) |
| |
| |
| if intersection / union > 0.6: |
| results.append(idx) |
| |
| return self.df.loc[results] |
| |
| elif method == 'prefix': |
| |
| 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] |
| |
| |
| transformations = [ |
| (r'ie', r'y'), |
| (r'y', r'ie'), |
| (r'ie', r'i'), |
| (r'i', r'ie'), |
| (r'io', r'eo'), |
| (r'eo', r'io'), |
| (r'on', r'an'), |
| (r'an', r'on'), |
| (r'om', r'am'), |
| (r'am', r'om'), |
| (r'rg', r'rh'), |
| (r'rh', r'rg'), |
| (r'ea', r'a'), |
| (r'a', r'ea'), |
| (r'eo', r'e') |
| ] |
| |
| 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']) |
| } |
| |
| |
| 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] != '']) |
| |
| |
| pos_counts = self.df['POS'].value_counts().to_dict() |
| stats["pos_distribution"] = pos_counts |
| |
| return stats |
|
|
|
|
| |
| if __name__ == "__main__": |
| oe_dict = OldEnglishDictionary() |
| |
| |
| print("\n=== SEARCH DEMONSTRATION ===") |
| |
| |
| print("\nSearching for entries with canonical key containing 'abelgan'...") |
| results = oe_dict.search("abelgan", mode="canonical") |
| oe_dict.display_results(results) |
| |
| |
| 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) |
| |
| |
| 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) |
| |
| |
| 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) |
| |
| |
| print("\nFinding entries similar to 'beon' using sound correspondences...") |
| results = oe_dict.find_similar("beon", method="sound") |
| oe_dict.display_results(results) |
| |
| |
| 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: |
| print(f" {pos}: {count}") |