fenic.api.functions.text
Text manipulation functions for Fenic DataFrames.
Functions:
-
array_join
–Joins an array of strings into a single string with a delimiter.
-
btrim
–Remove specified characters from both sides of strings in a column.
-
byte_length
–Calculate the byte length of each string in the column.
-
character_chunk
–Chunks a string column into chunks of a specified size (in characters) with an optional overlap.
-
compute_fuzzy_ratio
–Compute the similarity between two strings using a fuzzy string matching algorithm.
-
compute_fuzzy_token_set_ratio
–Compute fuzzy similarity using token set comparison.
-
compute_fuzzy_token_sort_ratio
–Compute fuzzy similarity after sorting tokens in each string.
-
concat
–Concatenates multiple columns or strings into a single string.
-
concat_ws
–Concatenates multiple columns or strings into a single string with a separator.
-
count_tokens
–Returns the number of tokens in a string using OpenAI's cl100k_base encoding (tiktoken).
-
extract
–Extracts structured data from text using template-based pattern matching.
-
jinja
–Render a Jinja template using values from the specified columns.
-
length
–Calculate the character length of each string in the column.
-
lower
–Convert all characters in a string column to lowercase.
-
ltrim
–Remove whitespace from the start of strings in a column.
-
parse_transcript
–Parses a transcript from text to a structured format with unified schema.
-
recursive_character_chunk
–Chunks a string column into chunks of a specified size (in characters) with an optional overlap.
-
recursive_token_chunk
–Chunks a string column into chunks of a specified size (in tokens) with an optional overlap.
-
recursive_word_chunk
–Chunks a string column into chunks of a specified size (in words) with an optional overlap.
-
regexp_replace
–Replace all occurrences of a pattern with a new string, treating pattern as a regular expression.
-
replace
–Replace all occurrences of a pattern with a new string, treating pattern as a literal string.
-
rtrim
–Remove whitespace from the end of strings in a column.
-
split
–Split a string column into an array using a regular expression pattern.
-
split_part
–Split a string and return a specific part using 1-based indexing.
-
title_case
–Convert the first character of each word in a string column to uppercase.
-
token_chunk
–Chunks a string column into chunks of a specified size (in tokens) with an optional overlap.
-
trim
–Remove whitespace from both sides of strings in a column.
-
upper
–Convert all characters in a string column to uppercase.
-
word_chunk
–Chunks a string column into chunks of a specified size (in words) with an optional overlap.
array_join
array_join(column: ColumnOrName, delimiter: str) -> Column
Joins an array of strings into a single string with a delimiter.
Parameters:
-
column
(ColumnOrName
) –The column to join
-
delimiter
(str
) –The delimiter to use
Returns: Column: A column containing the joined strings
Join array with comma
# Join array elements with comma
df.select(text.array_join(col("array_column"), ","))
Source code in src/fenic/api/functions/text.py
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 |
|
btrim
btrim(col: ColumnOrName, trim: Optional[Union[Column, str]]) -> Column
Remove specified characters from both sides of strings in a column.
This function removes all occurrences of the specified characters from both the beginning and end of each string in the column. If trim is a column expression, the characters to remove are determined dynamically from the values in that column.
Parameters:
-
col
(ColumnOrName
) –The input string column or column name to trim
-
trim
(Optional[Union[Column, str]]
) –The characters to remove from both sides (Default: whitespace) Can be a string or column expression.
Returns:
-
Column
(Column
) –A column containing the trimmed strings
Remove brackets from both sides
# Remove brackets from both sides of text
df.select(text.btrim(col("text"), "[]"))
Remove characters specified in a column
# Remove characters specified in a column
df.select(text.btrim(col("text"), col("chars")))
Source code in src/fenic/api/functions/text.py
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 |
|
byte_length
byte_length(column: ColumnOrName) -> Column
Calculate the byte length of each string in the column.
Parameters:
-
column
(ColumnOrName
) –The input string column to calculate byte lengths for
Returns:
-
Column
(Column
) –A column containing the byte length of each string
Get byte lengths
# Get the byte length of each string in the name column
df.select(text.byte_length(col("name")))
Source code in src/fenic/api/functions/text.py
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
|
character_chunk
character_chunk(column: ColumnOrName, chunk_size: int, chunk_overlap_percentage: int = 0) -> Column
Chunks a string column into chunks of a specified size (in characters) with an optional overlap.
The chunking is done by applying a simple sliding window across the text to create chunks of equal size. This approach does not attempt to preserve the underlying structure of the text.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name to chunk
-
chunk_size
(int
) –The size of each chunk in characters
-
chunk_overlap_percentage
(int
, default:0
) –The overlap between chunks as a percentage of the chunk size (Default: 0)
Returns:
-
Column
(Column
) –A column containing the chunks as an array of strings
Create character chunks
# Create chunks of 100 characters with 20% overlap
df.select(text.character_chunk(col("text"), 100, 20))
Source code in src/fenic/api/functions/text.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
|
compute_fuzzy_ratio
compute_fuzzy_ratio(column: ColumnOrName, other: Union[Column, str], method: FuzzySimilarityMethod = 'indel') -> Column
Compute the similarity between two strings using a fuzzy string matching algorithm.
This function computes a fuzzy similarity score between two string columns (or a string column and a literal string) for each row. It supports multiple well-known string similarity metrics, including Levenshtein, Damerau-Levenshtein, Jaro, Jaro-Winkler, and Hamming.
The returned score is a similarity percentage between 0 and 100, where: - 100 indicates the strings are identical - 0 indicates maximum dissimilarity (as defined by the method)
Based on https://rapidfuzz.github.io/RapidFuzz/Usage/fuzz.html#rapidfuzz.fuzz.ratio
Parameters:
-
column
(ColumnOrName
) –A string column or column name. This is the left-hand side of the comparison.
-
other
(Union[Column, str]
) –A second string column or literal string. This is the right-hand side of the comparison.
-
method
(FuzzySimilarityMethod
, default:'indel'
) –A string indicating which similarity method to use. Must be one of: -
"indel"
: Indel distance — counts only insertions and deletions (no substitutions); based on the Longest Common Subsequence. -"levenshtein"
: Levenshtein distance (edit distance) -"damerau_levenshtein"
: Damerau-Levenshtein distance (includes transpositions) -"jaro"
: Jaro similarity, accounts for transpositions and proximity -"jaro_winkler"
: Jaro-Winkler similarity, gives higher scores for common prefixes -"hamming"
: Hamming distance. Counts differing positions between two equal-length strings, padding shorter string if needed.
Returns:
-
Column
(Column
) –A double column with similarity scores in the range [0, 100].
Compare two columns
result = df.select(
compute_fuzzy_ratio(col("a"), col("b"), method="levenshtein").alias("sim")
)
Compare a column to a literal string
result = df.select(
compute_fuzzy_ratio(col("a"), "world", method="jaro").alias("sim_to_world")
)
Source code in src/fenic/api/functions/text.py
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 |
|
compute_fuzzy_token_set_ratio
compute_fuzzy_token_set_ratio(column: ColumnOrName, other: Union[Column, str], method: FuzzySimilarityMethod = 'indel') -> Column
Compute fuzzy similarity using token set comparison.
Tokenizes strings by whitespace, creates sets of unique tokens, then compares three combinations: diff1 vs diff2, intersection vs left set, and intersection vs right set. Returns the maximum similarity score. Useful for comparing strings where both word order and duplicates don't matter.
Based on https://rapidfuzz.github.io/RapidFuzz/Usage/fuzz.html#rapidfuzz.fuzz.token_set_ratio
Parameters:
-
column
(ColumnOrName
) –First string column to compare
-
other
(Union[Column, str]
) –Second string column or literal string to compare against
-
method
(FuzzySimilarityMethod
, default:'indel'
) –Similarity algorithm to use for comparison
Returns:
-
Column
–Double column with similarity scores between 0 and 100
Example
# df.select(compute_fuzzy_token_set_ratio(col("city"), "city of new york", "indel"))
# "new york city new" → unique tokens: {"city", "new", "york"}
# "city of new york" → unique tokens: {"city", "new", "of", "york"}
# intersection: {"city", "new", "york"}
# diff1: {} (empty)
# diff2: {"of"}
# Compares: diff1 vs diff2, intersection vs set1, intersection vs set2
# Returns max similarity score = 100
Source code in src/fenic/api/functions/text.py
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 |
|
compute_fuzzy_token_sort_ratio
compute_fuzzy_token_sort_ratio(column: ColumnOrName, other: Union[Column, str], method: FuzzySimilarityMethod = 'indel') -> Column
Compute fuzzy similarity after sorting tokens in each string.
Tokenizes strings by whitespace, sorts tokens alphabetically, concatenates them back into a string, then applies the specified similarity metric. Useful for comparing strings where word order doesn't matter.
Based on https://rapidfuzz.github.io/RapidFuzz/Usage/fuzz.html#rapidfuzz.fuzz.token_sort_ratio
Parameters:
-
column
(ColumnOrName
) –First string column to compare
-
other
(Union[Column, str]
) –Second string column or literal string to compare against
-
method
(FuzzySimilarityMethod
, default:'indel'
) –Similarity algorithm to use after token sorting
Returns:
-
Column
–Double column with similarity scores between 0 and 100
Example
# df.select(compute_fuzzy_token_sort_ratio(col("city"), "city new york", "levenshtein"))
# "new york city" → ["new", "york", "city"] → sorted → ["city", "new", "york"] → "city new york"
# "city new york" → ["city", "new", "york"] → sorted → ["city", "new", "york"] → "city new york"
# levenshtein similarity("city new york", "city new york") = 100
Source code in src/fenic/api/functions/text.py
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 |
|
concat
concat(*cols: ColumnOrName) -> Column
Concatenates multiple columns or strings into a single string.
Parameters:
-
*cols
(ColumnOrName
, default:()
) –Columns or strings to concatenate
Returns:
-
Column
(Column
) –A column containing the concatenated strings
Concatenate columns
# Concatenate two columns with a space in between
df.select(text.concat(col("col1"), lit(" "), col("col2")))
Source code in src/fenic/api/functions/text.py
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 |
|
concat_ws
concat_ws(separator: str, *cols: ColumnOrName) -> Column
Concatenates multiple columns or strings into a single string with a separator.
Parameters:
-
separator
(str
) –The separator to use
-
*cols
(ColumnOrName
, default:()
) –Columns or strings to concatenate
Returns:
-
Column
(Column
) –A column containing the concatenated strings
Concatenate with comma separator
# Concatenate columns with comma separator
df.select(text.concat_ws(",", col("col1"), col("col2")))
Source code in src/fenic/api/functions/text.py
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
|
count_tokens
count_tokens(column: ColumnOrName) -> Column
Returns the number of tokens in a string using OpenAI's cl100k_base encoding (tiktoken).
Parameters:
-
column
(ColumnOrName
) –The input string column.
Returns:
-
Column
(Column
) –A column with the token counts for each input string.
Count tokens in text
# Count tokens in a text column
df.select(text.count_tokens(col("text")))
Source code in src/fenic/api/functions/text.py
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
|
extract
extract(column: ColumnOrName, template: str) -> Column
Extracts structured data from text using template-based pattern matching.
Matches each string in the input column against a template pattern with named placeholders. Each placeholder can specify a format rule to handle different data types within the text.
Parameters:
-
column
(ColumnOrName
) –Input text column to extract from
-
template
(str
) –Template string with placeholders as
${field_name}
or${field_name:format}
Available formats: none, csv, json, quoted
Returns:
-
Column
(Column
) –Struct column with fields corresponding to template placeholders. All fields are strings except JSON fields which preserve their parsed type.
Template Syntax
${field_name}
- Extract field as plain text${field_name:csv}
- Parse as CSV field (handles quoted values)${field_name:json}
- Parse as JSON and preserve type${field_name:quoted}
- Extract quoted string (removes outer quotes)$
- Literal dollar sign
Raises:
-
ValidationError
–If template syntax is invalid
Basic extraction
text.extract(col("log"), "${date} ${level} ${message}")
# Input: "2024-01-15 ERROR Connection failed"
# Output: {date: "2024-01-15", level: "ERROR", message: "Connection failed"}
Mixed format extraction
text.extract(col("data"), 'Name: ${name:csv}, Price: ${price}, Tags: ${tags:json}')
# Input: 'Name: "Smith, John", Price: 99.99, Tags: ["a", "b"]'
# Output: {name: "Smith, John", price: "99.99", tags: ["a", "b"]}
Quoted field handling
text.extract(col("record"), 'Title: ${title:quoted}, Author: ${author}')
# Input: 'Title: "To Kill a Mockingbird", Author: Harper Lee'
# Output: {title: "To Kill a Mockingbird", author: "Harper Lee"}
Note
If a string doesn't match the template pattern, all extracted fields will be null.
Source code in src/fenic/api/functions/text.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
|
jinja
jinja(jinja_template: str, /, strict: bool = True, **columns: Column) -> Column
Render a Jinja template using values from the specified columns.
This function evaluates a Jinja2 template string for each row, using the provided columns as template variables. Only a subset of Jinja2 features is supported.
Parameters:
-
jinja_template
(str
) –A Jinja2 template string to render for each row. Variables are referenced using double braces: {{ variable_name }}
-
strict
(bool
, default:True
) –If True, when any of the provided columns has a None value for a row, the entire row's output will be None (template is not rendered). If False, None values are handled using Jinja2's null rendering behavior. Default is True.
-
**columns
(Column
, default:{}
) –Keyword arguments mapping variable names to columns. Each keyword becomes a variable in the template context.
Returns:
-
Column
(Column
) –A string column containing the rendered template for each row
Supported Features
- Variable substitution: {{ variable }}
- Struct/object field access: {{ user.name }}
- Array indexing with literals: {{ items[0] }}, {{ data["key"] }}
- For loops: {% for item in items %}...{% endfor %}
- If/elif/else conditionals: {% if condition %}...{% endif %}
- Loop variables: {{ loop.index }}, {{ loop.first }}, etc.
- Constants: {{ "literal string" }}, {{ 42 }}
Not Supported (use column expressions instead): - Filters: {{ name|upper }} → Use upper_name=fc.upper(col("name")) - Function calls: {{ len(items) }} → Use item_count=fc.array_size(col("items")) - Operators: {% if price > 100 %} → Use is_expensive=(col("price") > 100) - Arithmetic: {{ price * quantity }} → Use total=col("price") * col("quantity") - Dynamic indexing: {{ items[i] }} → Use item=(fc.col("items").get_item(col("index"))) - Variable assignment: {% set x = 5 %} → Pre-compute as column expression - Macros, includes, extends: Not supported
LLM prompt formatting with conditional context and examples
# Format prompts with user query, conditional context, and examples
prompt_template = '''
Answer the user's question.
{% if context %}
Context: {{ context }}
{% endif %}
{% if examples %}
Few-shot examples:
{% for ex in examples %}
Q: {{ ex.question }}
A: {{ ex.answer }}
{% endfor %}
{% endif %}
Question: {{ query }}
Please provide a {{ style }} response.'''
# Generate prompts with varying context based on query type
result = df.select(
text.jinja(
prompt_template,
# Direct columns
query=col("user_question"),
context=col("retrieved_context"), # Can be null for some rows
# Column expression for conditional logic
style=fc.when(col("query_type") == "technical", "detailed and technical")
.when(col("query_type") == "casual", "conversational")
.otherwise("clear and concise"),
# Array of examples (struct array)
examples=col("few_shot_examples") # Array of {question, answer} structs
).alias("llm_prompt")
)
Notes
- Template syntax is validated at query planning time
- Complex operations can use column expressions
- Arrays can only be iterated with {% for %} or accessed with literal indices
- Structs can only use literal field names
- Null values are rendered according to Jinja2's null rendering behavior
Source code in src/fenic/api/functions/text.py
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 |
|
length
length(column: ColumnOrName) -> Column
Calculate the character length of each string in the column.
Parameters:
-
column
(ColumnOrName
) –The input string column to calculate lengths for
Returns:
-
Column
(Column
) –A column containing the length of each string in characters
Get string lengths
# Get the length of each string in the name column
df.select(text.length(col("name")))
Source code in src/fenic/api/functions/text.py
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
lower
lower(column: ColumnOrName) -> Column
Convert all characters in a string column to lowercase.
Parameters:
-
column
(ColumnOrName
) –The input string column to convert to lowercase
Returns:
-
Column
(Column
) –A column containing the lowercase strings
Convert text to lowercase
# Convert all text in the name column to lowercase
df.select(text.lower(col("name")))
Source code in src/fenic/api/functions/text.py
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 |
|
ltrim
ltrim(col: ColumnOrName) -> Column
Remove whitespace from the start of strings in a column.
This function removes all whitespace characters (spaces, tabs, newlines) from the beginning of each string in the column.
Parameters:
-
col
(ColumnOrName
) –The input string column or column name to trim
Returns:
-
Column
(Column
) –A column containing the left-trimmed strings
Remove leading whitespace
# Remove whitespace from the start of text
df.select(text.ltrim(col("text")))
Source code in src/fenic/api/functions/text.py
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 |
|
parse_transcript
parse_transcript(column: ColumnOrName, format: TranscriptFormatType) -> Column
Parses a transcript from text to a structured format with unified schema.
Converts transcript text in various formats (srt, webvtt, generic) to a standardized structure with fields: index, speaker, start_time, end_time, duration, content, format. All timestamps are returned as floating-point seconds from the start.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name containing transcript text
-
format
(TranscriptFormatType
) –The format of the transcript ("srt", "webvtt", or "generic")
Returns:
-
Column
(Column
) –A column containing an array of structured transcript entries with unified schema:
- index: Optional[int] - Entry index (1-based)
- speaker: Optional[str] - Speaker name (for generic format)
- start_time: float - Start time in seconds
- end_time: Optional[float] - End time in seconds
- duration: Optional[float] - Duration in seconds
- content: str - Transcript content/text
- format: str - Original format ("srt", "webvtt", or "generic")
Examples:
>>> # Parse SRT format transcript
>>> df.select(text.parse_transcript(col("transcript"), "srt"))
>>> # Parse generic conversation transcript
>>> df.select(text.parse_transcript(col("transcript"), "generic"))
>>> # Parse WebVTT format transcript
>>> df.select(text.parse_transcript(col("transcript"), "webvtt"))
Source code in src/fenic/api/functions/text.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
|
recursive_character_chunk
recursive_character_chunk(column: ColumnOrName, chunk_size: int, chunk_overlap_percentage: int, chunking_character_set_custom_characters: Optional[list[str]] = None) -> Column
Chunks a string column into chunks of a specified size (in characters) with an optional overlap.
The chunking is performed recursively, attempting to preserve the underlying structure of the text by splitting on natural boundaries (paragraph breaks, sentence breaks, etc.) to maintain context. By default, these characters are ['\n\n', '\n', '.', ';', ':', ' ', '-', ''], but this can be customized.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name to chunk
-
chunk_size
(int
) –The size of each chunk in characters
-
chunk_overlap_percentage
(int
) –The overlap between each chunk as a percentage of the chunk size
-
chunking_character_set_custom_characters
(Optional
, default:None
) –List of alternative characters to split on. Note that the characters should be ordered from coarsest to finest desired granularity -- earlier characters in the list should result in fewer overall splits than later characters.
Returns:
-
Column
(Column
) –A column containing the chunks as an array of strings
Default character chunking
# Create chunks of at most 100 characters with 20% overlap
df.select(
text.recursive_character_chunk(col("text"), 100, 20).alias("chunks")
)
Custom character chunking
# Create chunks with custom split characters
df.select(
text.recursive_character_chunk(
col("text"),
100,
20,
['\n\n', '\n', '.', ' ', '']
).alias("chunks")
)
Source code in src/fenic/api/functions/text.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
|
recursive_token_chunk
recursive_token_chunk(column: ColumnOrName, chunk_size: int, chunk_overlap_percentage: int, chunking_character_set_custom_characters: Optional[list[str]] = None) -> Column
Chunks a string column into chunks of a specified size (in tokens) with an optional overlap.
The chunking is performed recursively, attempting to preserve the underlying structure of the text by splitting on natural boundaries (paragraph breaks, sentence breaks, etc.) to maintain context. By default, these characters are ['\n\n', '\n', '.', ';', ':', ' ', '-', ''], but this can be customized.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name to chunk
-
chunk_size
(int
) –The size of each chunk in tokens
-
chunk_overlap_percentage
(int
) –The overlap between each chunk as a percentage of the chunk size
-
chunking_character_set_custom_characters
(Optional
, default:None
) –List of alternative characters to split on. Note that the characters should be ordered from coarsest to finest desired granularity -- earlier characters in the list should result in fewer overall splits than later characters.
Returns:
-
Column
(Column
) –A column containing the chunks as an array of strings
Default token chunking
# Create chunks of at most 100 tokens with 20% overlap
df.select(
text.recursive_token_chunk(col("text"), 100, 20).alias("chunks")
)
Custom token chunking
# Create chunks with custom split characters
df.select(
text.recursive_token_chunk(
col("text"),
100,
20,
['\n\n', '\n', '.', ' ', '']
).alias("chunks")
)
Source code in src/fenic/api/functions/text.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 |
|
recursive_word_chunk
recursive_word_chunk(column: ColumnOrName, chunk_size: int, chunk_overlap_percentage: int, chunking_character_set_custom_characters: Optional[list[str]] = None) -> Column
Chunks a string column into chunks of a specified size (in words) with an optional overlap.
The chunking is performed recursively, attempting to preserve the underlying structure of the text by splitting on natural boundaries (paragraph breaks, sentence breaks, etc.) to maintain context. By default, these characters are ['\n\n', '\n', '.', ';', ':', ' ', '-', ''], but this can be customized.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name to chunk
-
chunk_size
(int
) –The size of each chunk in words
-
chunk_overlap_percentage
(int
) –The overlap between each chunk as a percentage of the chunk size
-
chunking_character_set_custom_characters
(Optional
, default:None
) –List of alternative characters to split on. Note that the characters should be ordered from coarsest to finest desired granularity -- earlier characters in the list should result in fewer overall splits than later characters.
Returns:
-
Column
(Column
) –A column containing the chunks as an array of strings
Default word chunking
# Create chunks of at most 100 words with 20% overlap
df.select(
text.recursive_word_chunk(col("text"), 100, 20).alias("chunks")
)
Custom word chunking
# Create chunks with custom split characters
df.select(
text.recursive_word_chunk(
col("text"),
100,
20,
['\n\n', '\n', '.', ' ', '']
).alias("chunks")
)
Source code in src/fenic/api/functions/text.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
|
regexp_replace
regexp_replace(src: ColumnOrName, pattern: Union[Column, str], replacement: Union[Column, str]) -> Column
Replace all occurrences of a pattern with a new string, treating pattern as a regular expression.
This method creates a new string column with all occurrences of the specified pattern replaced with a new string. The pattern is treated as a regular expression. If either pattern or replacement is a column expression, the operation is performed dynamically using the values from those columns.
Parameters:
-
src
(ColumnOrName
) –The input string column or column name to perform replacements on
-
pattern
(Union[Column, str]
) –The regular expression pattern to search for (can be a string or column expression)
-
replacement
(Union[Column, str]
) –The string to replace with (can be a string or column expression)
Returns:
-
Column
(Column
) –A column containing the strings with replacements applied
Replace digits with dashes
# Replace all digits with dashes
df.select(text.regexp_replace(col("text"), r"\d+", "--"))
Dynamic replacement using column values
# Replace using patterns from columns
df.select(text.regexp_replace(col("text"), col("pattern"), col("replacement")))
Complex pattern replacement
# Replace email addresses with [REDACTED]
df.select(text.regexp_replace(col("text"), r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", "[REDACTED]"))
Source code in src/fenic/api/functions/text.py
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 |
|
replace
replace(src: ColumnOrName, search: Union[Column, str], replace: Union[Column, str]) -> Column
Replace all occurrences of a pattern with a new string, treating pattern as a literal string.
This method creates a new string column with all occurrences of the specified pattern replaced with a new string. The pattern is treated as a literal string, not a regular expression. If either search or replace is a column expression, the operation is performed dynamically using the values from those columns.
Parameters:
-
src
(ColumnOrName
) –The input string column or column name to perform replacements on
-
search
(Union[Column, str]
) –The pattern to search for (can be a string or column expression)
-
replace
(Union[Column, str]
) –The string to replace with (can be a string or column expression)
Returns:
-
Column
(Column
) –A column containing the strings with replacements applied
Replace with literal string
# Replace all occurrences of "foo" in the "name" column with "bar"
df.select(text.replace(col("name"), "foo", "bar"))
Replace using column values
# Replace all occurrences of the value in the "search" column with the value in the "replace" column, for each row in the "text" column
df.select(text.replace(col("text"), col("search"), col("replace")))
Source code in src/fenic/api/functions/text.py
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 |
|
rtrim
rtrim(col: ColumnOrName) -> Column
Remove whitespace from the end of strings in a column.
This function removes all whitespace characters (spaces, tabs, newlines) from the end of each string in the column.
Parameters:
-
col
(ColumnOrName
) –The input string column or column name to trim
Returns:
-
Column
(Column
) –A column containing the right-trimmed strings
Remove trailing whitespace
# Remove whitespace from the end of text
df.select(text.rtrim(col("text")))
Source code in src/fenic/api/functions/text.py
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 |
|
split
split(src: ColumnOrName, pattern: str, limit: int = -1) -> Column
Split a string column into an array using a regular expression pattern.
This method creates an array column by splitting each value in the input string column at matches of the specified regular expression pattern.
Parameters:
-
src
(ColumnOrName
) –The input string column or column name to split
-
pattern
(str
) –The regular expression pattern to split on
-
limit
(int
, default:-1
) –Maximum number of splits to perform (Default: -1 for unlimited). If > 0, returns at most limit+1 elements, with remainder in last element.
Returns:
-
Column
(Column
) –A column containing arrays of substrings
Split on whitespace
# Split on whitespace
df.select(text.split(col("text"), r"\s+"))
Split with limit
# Split on whitespace, max 2 splits
df.select(text.split(col("text"), r"\s+", limit=2))
Source code in src/fenic/api/functions/text.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 |
|
split_part
split_part(src: ColumnOrName, delimiter: Union[Column, str], part_number: Union[Column, int]) -> Column
Split a string and return a specific part using 1-based indexing.
Splits each string by a delimiter and returns the specified part. If the delimiter is a column expression, the split operation is performed dynamically using the delimiter values from that column.
Behavior: - If any input is null, returns null - If part_number is out of range of split parts, returns empty string - If part_number is 0, throws an error - If part_number is negative, counts from the end of the split parts - If the delimiter is an empty string, the string is not split
Parameters:
-
src
(ColumnOrName
) –The input string column or column name to split
-
delimiter
(Union[Column, str]
) –The delimiter to split on (can be a string or column expression)
-
part_number
(Union[Column, int]
) –Which part to return (1-based integer index or column expression)
Returns:
-
Column
(Column
) –A column containing the specified part from each split string
Get second part of comma-separated values
# Get second part of comma-separated values
df.select(text.split_part(col("text"), ",", 2))
Get last part using negative index
# Get last part using negative index
df.select(text.split_part(col("text"), ",", -1))
Use dynamic delimiter from column
# Use dynamic delimiter from column
df.select(text.split_part(col("text"), col("delimiter"), 1))
Source code in src/fenic/api/functions/text.py
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 |
|
title_case
title_case(column: ColumnOrName) -> Column
Convert the first character of each word in a string column to uppercase.
Parameters:
-
column
(ColumnOrName
) –The input string column to convert to title case
Returns:
-
Column
(Column
) –A column containing the title case strings
Convert text to title case
# Convert text in the name column to title case
df.select(text.title_case(col("name")))
Source code in src/fenic/api/functions/text.py
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 |
|
token_chunk
token_chunk(column: ColumnOrName, chunk_size: int, chunk_overlap_percentage: int = 0) -> Column
Chunks a string column into chunks of a specified size (in tokens) with an optional overlap.
The chunking is done by applying a simple sliding window across the text to create chunks of equal size. This approach does not attempt to preserve the underlying structure of the text.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name to chunk
-
chunk_size
(int
) –The size of each chunk in tokens
-
chunk_overlap_percentage
(int
, default:0
) –The overlap between chunks as a percentage of the chunk size (Default: 0)
Returns:
-
Column
(Column
) –A column containing the chunks as an array of strings
Create token chunks
# Create chunks of 100 tokens with 20% overlap
df.select(text.token_chunk(col("text"), 100, 20))
Source code in src/fenic/api/functions/text.py
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
|
trim
trim(column: ColumnOrName) -> Column
Remove whitespace from both sides of strings in a column.
This function removes all whitespace characters (spaces, tabs, newlines) from both the beginning and end of each string in the column.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name to trim
Returns:
-
Column
(Column
) –A column containing the trimmed strings
Remove whitespace from both sides
# Remove whitespace from both sides of text
df.select(text.trim(col("text")))
Source code in src/fenic/api/functions/text.py
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 |
|
upper
upper(column: ColumnOrName) -> Column
Convert all characters in a string column to uppercase.
Parameters:
-
column
(ColumnOrName
) –The input string column to convert to uppercase
Returns:
-
Column
(Column
) –A column containing the uppercase strings
Convert text to uppercase
# Convert all text in the name column to uppercase
df.select(text.upper(col("name")))
Source code in src/fenic/api/functions/text.py
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
|
word_chunk
word_chunk(column: ColumnOrName, chunk_size: int, chunk_overlap_percentage: int = 0) -> Column
Chunks a string column into chunks of a specified size (in words) with an optional overlap.
The chunking is done by applying a simple sliding window across the text to create chunks of equal size. This approach does not attempt to preserve the underlying structure of the text.
Parameters:
-
column
(ColumnOrName
) –The input string column or column name to chunk
-
chunk_size
(int
) –The size of each chunk in words
-
chunk_overlap_percentage
(int
, default:0
) –The overlap between chunks as a percentage of the chunk size (Default: 0)
Returns:
-
Column
(Column
) –A column containing the chunks as an array of strings
Create word chunks
# Create chunks of 100 words with 20% overlap
df.select(text.word_chunk(col("text"), 100, 20))
Source code in src/fenic/api/functions/text.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
|