### Python API for IPA Segment Features (panphon) Source: https://github.com/dmort27/panphon/blob/master/README.md Demonstrates using the FeatureTable class from the panphon module to access phonological features of IPA segments. It shows how to get feature vectors for words and compare segment features. ```python import panphon >>> ft = panphon.FeatureTable() >>> ft.word_fts(u'swit') [, , , ] >>> ft.word_fts(u'swit')[0].match({'cor': 1}) True >>> ft.word_fts(u'swit')[0] >= {'cor': 1} True >>> ft.word_fts(u'swit')[1] >= {'cor': 1} False >>> ft.word_to_vector_list(u'sauɹ', numeric=False) [[u'-', u'-', u'+', u'+', u'-', u'-', u'-', u'0', u'-', u'-', u'-', u'+', u'+', u'-', u'-', u'-', u'-', u'-', u'-', u'-', u'0', u'-'], [u'+', u'+', u'-', u'+', u'-', u'-', u'-', u'0', u'+', u'-', u'-', u'0', u'-', u'0', u'-', u'-', u'+', u'+', u'-', u'-', u'+', u'-'], [u'+', u'+', u'-', u'+', u'-', u'-', u'-', u'0', u'+', u'-', u'-', u'0', u'-', u'0', u'+', u'+', u'-', u'+', u'+', u'-', u'+', u'-'], [u'-', u'+', u'-', u'+', u'-', u'-', u'-', u'0', u'+', u'-', u'-', u'+', u'+', u'-', u'-', u'+', u'-', u'+', u'+', u'-', u'0', u'-']] ``` -------------------------------- ### Calculate Distances Using PanPhon Distance Module in Python Source: https://github.com/dmort27/panphon/blob/master/README.md Shows how to use the `Distance` class from the `panphon.distance` module to compute various phonetic distances between strings. This example specifically demonstrates the `dolgo_prime_distance` method, which calculates Levenshtein distance after collapsing segments into enhanced equivalence classes. ```python >>> import panphon.distance >>> dst = panphon.distance.Distance() >>> dst.dolgo_prime_distance(u'pops', u'bobz') 0 >>> dst.dolgo_prime_distance(u'pops', u'bobo') 1 ``` -------------------------------- ### Initialize PanPhon FeatureTable Source: https://context7.com/dmort27/panphon/llms.txt Initializes the FeatureTable, which holds the core IPA segment-to-features database. This table maps IPA segments to feature vectors using a defined set of phonological features. ```python import panphon # Create a feature table with the default 'spe+' feature set ft = panphon.FeatureTable() # The feature table contains mappings from IPA segments to feature vectors # with 22 phonological features ``` -------------------------------- ### Generate IPA Character Database using generate_ipa_all.py Source: https://github.com/dmort27/panphon/blob/master/README.rst Shows how to execute the generate_ipa_all.py script to create a comprehensive IPA character database (ipa_all.csv). This script uses YAML-defined rules for diacritics and sorting, based on input CSV and YAML files. Ensure you are in the panphon data directory when running. ```bash $ generate_ipa_all.py ipa_bases.csv -d diacritic_definitions.yml -s sort_order.yml ipa_all.csv ``` -------------------------------- ### Generate IPA All Script Usage Source: https://github.com/dmort27/panphon/blob/master/README.md This bash command demonstrates how to use the `generate_ipa_all.py` script to create an IPA segment features file. It takes input CSV and YAML files defining IPA bases, diacritic definitions, and sort order, and outputs `ipa_all.csv`. ```bash generate_ipa_all.py ipa_bases.csv -d diacritic_definitions.yml -s sort_order.yml ipa_all.csv ``` -------------------------------- ### Convert X-SAMPA to IPA using panphon Source: https://context7.com/dmort27/panphon/llms.txt Converts strings from X-SAMPA phonetic notation to Unicode IPA using the panphon.xsampa.XSampa class. It handles simple conversions, complex characters, word lists, and can be integrated with FeatureTable for a workflow involving feature vectors. ```python from panphon.xsampa import XSampa xs = XSampa() # Convert X-SAMPA string to IPA ipa = xs.convert('hEl@U') print(ipa) # Output: 'hɛləʊ' # More complex example with special characters ipa2 = xs.convert('tS\IN') print(ipa2) # Output: 'tʃɪŋ' # Convert word list (space-delimited) ipa3 = xs.convert('D@') print(ipa3) # Output: 'ðə' # Works with FeatureTable for integrated workflow import panphon ft = panphon.FeatureTable() vectors = ft.word_to_vector_list('h{t', numeric=True, xsampa=True) # Converts 'h{t' (X-SAMPA) → 'hæt' (IPA) → feature vectors ``` -------------------------------- ### Construct Segment Objects in Python Source: https://github.com/dmort27/panphon/blob/master/README.md Demonstrates two primary methods for creating Segment objects in Python. Both involve specifying feature names and their corresponding values. The first method uses a list of feature names and a dictionary of feature values. The second method uses a list of feature names and a feature string (ftstr) for initialization. Feature values can be -1, 0, or 1. ```python >>> from panphon.segment import Segment >>> Segment(['syl', 'son', 'cont'], {'syl': -1, 'son': -1, 'cont': 1}) >>> Segment(['syl', 'son', 'cont'], ftstr='[-syl, -son, +cont]') ``` -------------------------------- ### Python API: Accessing IPA Segment Features with panphon Source: https://github.com/dmort27/panphon/blob/master/README.rst Demonstrates using the panphon module's FeatureTable class to access phonological features of IPA segments. This includes checking feature matches, segmenting words, and retrieving feature sets for words. It requires the 'panphon' library. ```python import panphon.panphon as panphon ft = panphon.FeatureTable() ft.ftr_match(set([(u'+', u'syl')]), u'a') ft.segs(u'pʲãk') ft.word_fts(u'pʲãk') ``` -------------------------------- ### Manipulate Segment Features with PanPhon Source: https://context7.com/dmort27/panphon/llms.txt Demonstrates how to create Segments, find intersections of features using `intersection()` or the `&` operator, and check for negative matches. ```python from panphon import Segment feature_names = ['syl', 'son', 'cont', 'voi'] seg = Segment(feature_names, {'syl': 1, 'son': 1, 'cont': 1, 'voi': 1}) # Negative example matches_neg = seg >= {'son': 1, 'cont': 1} print(matches_neg) # Output: False # Find intersection of features (features that match) seg2 = Segment(feature_names, {'syl': -1, 'son': 1, 'cont': -1, 'voi': 1}) intersection = seg.intersection(seg2) print(intersection) # Output: # Only matching features # Using & operator (alias for intersection) intersection_alt = seg & seg2 print(intersection_alt) # Output: ``` -------------------------------- ### Calculate Segment Sonority with PanPhon Source: https://context7.com/dmort27/panphon/llms.txt Demonstrates how to use the Sonority class to determine the sonority hierarchy of IPA segments on a scale of 1 to 9. ```python from panphon.sonority import Sonority # Initialize sonority calculator son = Sonority() # Get sonority values (scale 1-9) # Vowels have highest sonority, obstruents lowest sonority_a = son.sonority('a') print(f"Sonority of 'a': {sonority_a}") # Output: Sonority of 'a': 9 # Low vowel sonority_i = son.sonority('i') print(f"Sonority of 'i': {sonority_i}") # Output: Sonority of 'i': 8 # High vowel sonority_l = son.sonority('l') print(f"Sonority of 'l': {sonority_l}") # Output: Sonority of 'l': 6 # Liquid SONORITY_S = son.sonority('s') print(f"Sonority of 's': {SONORITY_S}") # Output: Sonority of 's': 3 # Voiceless fricative SONORITY_P = son.sonority('p') print(f"Sonority of 'p': {SONORITY_P}") # Output: Sonority of 'p': 1 # Voiceless stop ``` -------------------------------- ### Segment IPA Strings with PanPhon Source: https://context7.com/dmort27/panphon/llms.txt Shows how to parse IPA text into segments, validate if a word consists of valid IPA segments, and handle potentially invalid characters. ```python import panphon ft = panphon.FeatureTable() # Segment a word into IPA segments segments = ft.ipa_segs('ætʃuŋ') print(segments) # Output: ['æ', 't͡ʃ', 'u', 'ŋ'] # Check if a word consists of valid IPA segments is_valid = ft.validate_word('hɛloʊ') print(is_valid) # Output: True is_valid_invalid = ft.validate_word('hello') print(is_valid_invalid) # Output: False (ASCII, not IPA) # Get segments including invalid characters segments_safe = ft.segs_safe('hɛl2o') print(segments_safe) # Output: ['h', 'ɛ', 'l', '2', 'o'] # '2' preserved as invalid # Filter to only valid IPA segments segments_filtered = ft.filter_segs(['h', 'ɛ', 'l', '2', 'o']) print(segments_filtered) # Output: ['h', 'ɛ', 'l', 'o'] ``` -------------------------------- ### Create and Query Segment Objects Source: https://context7.com/dmort27/panphon/llms.txt Programmatically creates Segment objects using feature dictionaries or strings. Allows querying individual features, updating feature values, and retrieving feature vectors in numeric or string format. ```python from panphon.segment import Segment feature_names = ['syl', 'son', 'cont', 'voi'] seg1 = Segment(feature_names, {'syl': -1, 'son': -1, 'cont': 1, 'voi': -1}) print(seg1) # Output: # Alternative: create from feature string seg2 = Segment(feature_names, ftstr='[-syl, -son, +cont, -voi]') print(seg2) # Output: # Query and update features print(seg1['son']) # Output: -1 seg1['son'] = 1 print(seg1) # Output: # Bulk update seg1.update({'son': -1, 'cont': -1}) print(seg1) # Output: # Get feature values as vectors print(seg1.numeric()) # Output: [-1, -1, -1, -1] print(seg1.strings()) # Output: ['-', '-', '-', '-'] ``` -------------------------------- ### Calculate Phonological Distances with PanPhon Source: https://context7.com/dmort27/panphon/llms.txt Demonstrates calculating various phonological distances between words, including feature-based edit distance, Dolgopolsky distance, and Levenshtein distance. ```python import panphon.distance dst = panphon.distance.Distance() # Feature-based edit distance (all features equally weighted) # Each feature change costs 1/22, insertions/deletions cost ~1 distance = dst.feature_edit_distance('pɑp', 'bɑb') print(f"Feature distance: {distance:.3f}") # Output: Feature distance: 0.091 # Two voicing changes # Hamming feature edit distance (counts different features) # Insertions/deletions cost 1, substitution = hamming distance / 22 hamming_dist = dst.hamming_feature_edit_distance('pɑp', 'bɑb') print(f"Hamming distance: {hamming_dist:.3f}") # Output: Hamming distance: 0.091 # Weighted feature edit distance (subjective feature weights) # More stable features have higher costs weighted_dist = dst.weighted_feature_edit_distance('pɑp', 'bɑb') print(f"Weighted distance: {weighted_dist:.3f}") # Output: Weighted distance: 0.181 # Normalized by maximum word length normalized = dst.feature_edit_distance_div_maxlen('pɑp', 'bɑbəl') print(f"Normalized distance: {normalized:.3f}") # Output: Normalized distance: 0.036 # Dolgopolsky Prime distance collapses segments into sound classes # then computes Levenshtein distance on the simplified representation distance = dst.dolgo_prime_distance('pops', 'bobz') print(distance) # Output: 0 # All map to same classes: P-O-P-S ≈ P-O-P-S distance2 = dst.dolgo_prime_distance('pops', 'bobo') print(distance2) # Output: 1 # Last segment differs # Normalized version (divided by max length) normalized = dst.dolgo_prime_distance_div_maxlen('pops', 'bobo') print(f"Normalized: {normalized:.3f}") # Output: Normalized: 0.250 # Map individual words to Dolgopolsky classes mapped = dst.map_to_dolgo_prime('pəbətəg') print(mapped) # Output: 'PPTPK' # Shows consonant classes # Fast C implementation using editdistance library distance = dst.fast_levenshtein_distance('kitten', 'sitting') print(distance) # Output: 3 # Three edits needed # Normalized by maximum length norm_distance = dst.fast_levenshtein_distance_div_maxlen('kitten', 'sitting') print(f"Normalized: {norm_distance:.3f}") # Output: Normalized: 0.429 # 3/7 # Pure Python implementation (slower, for reference) python_dist = dst.levenshtein_distance('cat', 'hat') print(python_dist) # Output: 1 ``` -------------------------------- ### Vector Representations of Segment Objects in Python Source: https://github.com/dmort27/panphon/blob/master/README.md Demonstrates how to obtain vector representations of Segment objects. The `numeric` method returns the feature values as a list of integers, while the `strings` method returns them as a list of Unicode strings (e.g., '-', '+'). ```python >>> a = Segment(['syl', 'son', 'cont'], {'syl': -1, 'son': -1, 'cont': 1}) >>> a.numeric() [-1, -1, 1] >>> a.strings() [u'-', u'-', u'+'] ``` -------------------------------- ### Convert IPA Word to Segments and Features Source: https://context7.com/dmort27/panphon/llms.txt Converts an IPA word into a list of Segment objects, each representing an IPA segment with its associated phonological features. Supports checking feature matches using dictionary or operator syntax. ```python import panphon ft = panphon.FeatureTable() # Convert a word to a list of Segment objects segments = ft.word_fts('swit') # Returns: [, , ...] # Access individual segment first_segment = segments[0] print(first_segment) # Output: # Check if a segment matches specific features using dictionary notation is_coronal = first_segment.match({'cor': 1}) print(is_coronal) # Output: True # Alternative syntax using >= operator is_coronal_alt = first_segment >= {'cor': 1} print(is_coronal_alt) # Output: True ``` -------------------------------- ### Set Operations for Segment Objects in Python Source: https://github.com/dmort27/panphon/blob/master/README.md Illustrates set operations on Segment objects, specifically the `match` method (aliased by `>=`) and the `intersection` method (aliased by `&`). The `match` method checks if a segment contains a superset of features from a given dictionary. The `intersection` method returns a new Segment object containing only the shared features. ```python >>> a = Segment(['syl', 'son', 'cont'], {'syl': -1, 'son': -1, 'cont': 1}) >>> a.match({'son': -1, 'cont': 1}) True >>> a.match({'son': -1, 'cont': -1}) False >>> a >= {'son': -1, 'cont': 1} True >>> a >= {'son': 1, 'cont': 1} False >>> a.intersection({'syl': -1, 'son': 1, 'cont': -1}) >>> a & {'syl': -1, 'son': 1, 'cont': -1} ``` -------------------------------- ### Convert IPA Word to Feature Vectors (List) Source: https://context7.com/dmort27/panphon/llms.txt Retrieves phonological features for an IPA word as lists of strings ('+', '-', '0') or numeric values (-1, 0, 1). Supports conversion from X-SAMPA notation. ```python import panphon ft = panphon.FeatureTable() # Convert to list of string vectors ('+', '-', '0') string_vectors = ft.word_to_vector_list('sauɹ', numeric=False) print(string_vectors[0][:5]) # First 5 features of first segment # Output: ['-', '-', '+', '+', '-'] # Convert to list of numeric vectors (-1, 0, 1) numeric_vectors = ft.word_to_vector_list('sauɹ', numeric=True) print(numeric_vectors[0][:5]) # Output: [-1, -1, 1, 1, -1] # Support for X-SAMPA input xsampa_vectors = ft.word_to_vector_list('s{u\', numeric=True, xsampa=True) # Converts X-SAMPA to IPA, then to feature vectors ``` -------------------------------- ### Calculate Weighted Edit Distance with panphon.distance Source: https://github.com/dmort27/panphon/blob/master/README.rst Demonstrates how to use the panphon.distance module to calculate edit distances between strings. The distance calculation is weighted based on feature edits and their variability. This module is useful for phonetic comparison tasks. ```python import panphon.distance dst = panphon.distance.Distance() dst.dogol_prime_distance(u'pops', u'bobz') dst.dogol_prime_distance(u'pops', u'bobo') ``` -------------------------------- ### Convert Feature Vectors to IPA Word - Python Source: https://context7.com/dmort27/panphon/llms.txt Converts a list of feature vectors back into an IPA word using PanPhon's FeatureTable. It can perform exact matching or fuzzy searching for the closest segment if an exact match is not found. The output can also be in X-SAMPA format. Requires a list of lists, where each inner list is a feature vector. ```python import panphon ft = panphon.FeatureTable() # Example feature vectors vectors = [ [-1, -1, 1, 1, -1, -1, -1, 0, -1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 0, -1], [1, 1, -1, 1, -1, -1, -1, 0, 1, -1, -1, 0, -1, 0, -1, -1, 1, 1, -1, -1, 1, -1], [-1, -1, 1, 1, -1, -1, -1, 0, -1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 0, -1] ] # Convert to IPA word (exact match) try: word = ft.vector_list_to_word(vectors) print(f"IPA Word: {word}") except ValueError as e: print(f"Error: {e}") # Convert to IPA word (fuzzy search) word_fuzzy = ft.vector_list_to_word(vectors, fuzzy_search=True) print(f"Fuzzy IPA Word: {word_fuzzy}") # Convert to X-SAMPA word (fuzzy search) word_xsampa = ft.vector_list_to_word(vectors, xsampa=True, fuzzy_search=True) print(f"X-SAMPA Word: {word_xsampa}") ``` -------------------------------- ### Convert IPA Word to Feature Matrix (NumPy) Source: https://context7.com/dmort27/panphon/llms.txt Generates a NumPy array representation of phonological features for a given IPA word, suitable for machine learning tasks. Allows specifying a subset of features of interest. ```python import panphon ft = panphon.FeatureTable() # Specify features of interest and convert word to array # Each row is a segment, each column is a feature value feature_array = ft.word_array(['syl', 'son', 'cont'], 'sɑlti') print(feature_array) # Output: # array([[-1, -1, 1], # s: [-syl, -son, +cont] # [ 1, 1, 1], # ɑ: [+syl, +son, +cont] # [-1, 1, 1], # l: [-syl, +son, +cont] # [-1, -1, -1], # t: [-syl, -son, -cont] # [ 1, 1, 1]]) # i: [+syl, +son, +cont] ``` -------------------------------- ### Match Feature Patterns in Segments Source: https://context7.com/dmort27/panphon/llms.txt Uses panphon.FeatureTable to find segments or words matching specific feature patterns. It supports fixed-width pattern matching and searching for all segments with a given feature mask. It also allows compiling regex from feature string notation. ```python import panphon ft = panphon.FeatureTable() # Fixed-width pattern matching on words # Each dict in the pattern matches one segment position pattern = [ {'voi': -1, 'cont': 1}, # Voiceless fricative {'syl': 1}, # Vowel {'voi': -1, 'cont': 1} # Voiceless fricative ] # Match returns the segments if pattern matches, None otherwise match = ft.match_pattern(pattern, 'sas') if match: print("Pattern matched!") print(match) # Output: [, , ] no_match = ft.match_pattern(pattern, 'dad') print(no_match) # Output: None # 'd' is voiced, doesn't match pattern # Find all segments matching a feature mask voiceless_fricatives = ft.all_segs_matching_fts({'voi': -1, 'cont': 1, 'son': -1}) print(voiceless_fricatives[:5]) # Output: ['θ̠ʃʲ', 'θʲʃ', 'θʃʲ', 's̠ʲ', 'θʃ'] # Longest matches first # Compile regex from feature string notation regex = ft.compile_regex_from_str('[+syl][-son +cont]') # Matches: vowel followed by fricative matches = regex.findall('asaftag') print(matches) # Output: ['as', 'af'] ``` -------------------------------- ### Calculate Sonority Profile of a Syllable Source: https://context7.com/dmort27/panphon/llms.txt Calculates the sonority of each segment in a syllable and prints the resulting sonority profile. This is useful for analyzing sonority sequencing principles in phonology. ```python import panphon.sonority as son syllable = ['p', 'l', 'a', 'n', 't'] sonority_profile = [son.sonority(seg) for seg in syllable] print(sonority_profile) # Output: [1, 6, 9, 5, 1] ``` -------------------------------- ### Create Bag of Features Representation - Python Source: https://context7.com/dmort27/panphon/llms.txt Generates a bag-of-features representation for a given word. This creates a frequency vector where each dimension corresponds to a feature-value combination (e.g., +syl, 0syl, -syl). This is useful for machine learning feature extraction and comparing words based on their feature distributions. Requires a string word as input. ```python import panphon import numpy as np ft = panphon.FeatureTable() # Convert word to bag-of-features bag = ft.bag_of_features('kæt') print(f"Bag shape: {bag.shape}") print(f"First 9 dimensions: {bag[:9]}") # Compare with another word bag2 = ft.bag_of_features('tæk') print(f"First 9 dimensions (tæk): {bag2[:9]}") # Calculate cosine similarity similarity = np.dot(bag, bag2) / (np.linalg.norm(bag) * np.linalg.norm(bag2)) print(f"Cosine similarity: {similarity:.3f}") ``` -------------------------------- ### Python: Convert Words to Feature Arrays with panphon.word2array Source: https://github.com/dmort27/panphon/blob/master/README.rst Illustrates the use of the panphon.word2array function to convert a list of feature names and a panphon word (obtained from FeatureTable().word_fts()) into a NumPy array. Each row in the array represents a segment, and each column represents a specified feature. Requires 'panphon' and 'numpy'. ```python import panphon ft=panphon.FeatureTable() panphon.word2array(['syl', 'son', 'cont'], ft.word_fts(u'snik')) ``` -------------------------------- ### Query and Update Segment Objects in Python Source: https://github.com/dmort27/panphon/blob/master/README.md Shows how to access and modify feature values of a Segment object using dictionary-like syntax. Features can be queried by their name to retrieve their integer value. New feature-value pairs can be assigned directly, and the `update` method can be used to modify multiple features at once. ```python >>> a = Segment(['syl', 'son', 'cont'], {'syl': -1, 'son': -1, 'cont': 1}) >>> a >>> a['syl'] -1 >>> a['son'] = 1 >>> a >>> a.update({'son': -1, 'cont': -1}) >>> a ``` -------------------------------- ### Convert Words to Feature Arrays (panphon) Source: https://github.com/dmort27/panphon/blob/master/README.md Illustrates the `word_array` function from the panphon module, which converts a panphon word (obtained from `FeatureTable().word_fts()`) into a NumPy array. Each row represents a segment, and each column represents a specified feature. ```python import panphon >>> ft=panphon.FeatureTable() >>> ft.word_array(['syl', 'son', 'cont'], u'sɑlti') array([[-1, -1, 1], [ 1, 1, 1], [-1, 1, 1], [-1, -1, -1], [ 1, 1, 1]]) ``` -------------------------------- ### Calculate Phoneme and Feature Error Rates - Python Source: https://context7.com/dmort27/panphon/llms.txt Calculates the Phoneme Error Rate (PER) and Feature Error Rate (FER) between hypothesized and reference phoneme sequences. PER uses simple edit distance, while FER uses feature edit distance for partial credit. Requires lists of phoneme strings for hypotheses and references. ```python import panphon.distance as dst hypotheses = ["pən" "aɪ" "tə"] # Example hypotheses references = ["pən" "aɪ" "tə"] # Example references # Phoneme Error Rate (PER) per = dst.phoneme_error_rate(hypotheses, references) print(f"Phoneme Error Rate: {per:.3f}") # Feature Error Rate (FER) fer = dst.feature_error_rate(hypotheses, references) print(f"Feature Error Rate: {fer:.3f}") ``` -------------------------------- ### Count and Filter Segments by Features Source: https://context7.com/dmort27/panphon/llms.txt Queries segment inventories based on feature specifications using panphon.FeatureTable. It includes functions to count segments matching a feature mask, check if all segments meet a specification, determine if any segment matches, and find shared features across multiple segments. ```python import panphon ft = panphon.FeatureTable() # Example inventory inventory = ['p', 't', 'k', 'b', 'd', 'g', 'm', 'n', 'ŋ', 'a', 'i', 'u'] # Count segments matching a feature mask voiceless_count = ft.fts_count({'voi': -1}, inventory) print(f"Voiceless segments: {voiceless_count}") # Output: Voiceless segments: 3 # p, t, k nasal_count = ft.fts_count({'nas': 1}, inventory) print(f"Nasal segments: {nasal_count}") # Output: Nasal segments: 3 # m, n, ŋ # Check if all segments match a feature specification all_consonantal = ft.fts_match_all({'cons': 1}, ['p', 't', 'k']) print(f"All consonantal: {all_consonantal}") # Output: All consonantal: True all_voiced = ft.fts_match_all({'voi': 1}, ['b', 'd', 'a']) print(f"All voiced: {all_voiced}") # Output: All voiced: True # Check if any segment matches has_nasal = ft.fts_match_any({'nas': 1}, ['p', 't', 'm']) print(f"Has nasal: {has_nasal}") # Output: Has nasal: True # Find feature intersection across multiple segments stops = ['p', 't', 'k', 'b', 'd', 'g'] shared_features = ft.fts_intersection(stops) print(shared_features) # Output: ``` -------------------------------- ### Perform Set Operations on Segments Source: https://context7.com/dmort27/panphon/llms.txt Enables checking if a segment matches a specific feature mask (superset relationship) using the `match` method or the `>=` operator. This is useful for querying feature subsets. ```python from panphon.segment import Segment feature_names = ['syl', 'son', 'cont', 'voi'] seg = Segment(feature_names, {'syl': -1, 'son': -1, 'cont': 1, 'voi': 1}) # Check if segment matches a feature mask (superset relationship) matches = seg.match({'son': -1, 'cont': 1}) print(matches) # Output: True # Using >= operator (alias for match) matches_alt = seg >= {'son': -1, 'cont': 1} print(matches_alt) # Output: True ``` -------------------------------- ### Calculate Phoneme Error Rate (PER) Source: https://context7.com/dmort27/panphon/llms.txt Measures the phoneme-level accuracy between hypothesized and reference transcriptions using panphon.distance.Distance. This is essential for evaluating speech recognition systems or phonological rule applications. ```python import panphon.distance dst = panphon.distance.Distance() # Hypothesized transcriptions from a system hypotheses = ['kæt', 'dɔg', 'haʊs'] # Reference (correct) transcriptions references = ['kæt', 'dɑg', 'haʊs'] # Calculate phoneme error rate (PER) # PER = (Substitutions + Insertions + Deletions) / Number of reference phonemes # This calculation would typically involve comparing sequences and finding the minimum edit distance. ``` -------------------------------- ### Calculate Segment Distance Source: https://context7.com/dmort27/panphon/llms.txt Computes various distances between two segments using the panphon.segment.Segment class. Supported metrics include feature distance (sum of absolute differences), normalized distance, and Hamming distance. An alternative syntax using the subtraction operator for normalized distance is also demonstrated. ```python from panphon.segment import Segment feature_names = ['syl', 'son', 'cons', 'cont', 'voi', 'ant', 'cor', 'lab'] seg_p = Segment(feature_names, {'syl': -1, 'son': -1, 'cons': 1, 'cont': -1, 'voi': -1, 'ant': 1, 'cor': -1, 'lab': 1}) seg_b = Segment(feature_names, {'syl': -1, 'son': -1, 'cons': 1, 'cont': -1, 'voi': 1, 'ant': 1, 'cor': -1, 'lab': 1}) # Feature distance (sum of absolute differences) distance = seg_p.distance(seg_b) print(f"Distance: {distance}") # Output: Distance: 2 # Differs in voicing: abs(-1 - 1) = 2 # Normalized distance (divided by number of features) norm_distance = seg_p.norm_distance(seg_b) print(f"Normalized distance: {norm_distance:.3f}") # Output: Normalized distance: 0.250 # 2/8 # Hamming distance (count of different features) hamming = seg_p.hamming_distance(seg_b) print(f"Hamming distance: {hamming}") # Output: Hamming distance: 1 # One feature differs # Alternative syntax using subtraction operator dist_op = seg_p - seg_b print(f"Distance (operator): {dist_op:.3f}") # Output: Distance (operator): 0.250 # Same as norm_distance ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.