Package: pyplaceholder
pyplaceholderA placeholder detector in text or in text files and other placeholder utilities.
A placeholder is a piece of text delimited by some symbolsDetect the placeholdersReplace text placeholdersCheck if there are placeholdersCount placeholdersGet the placeholder contentsDetect the placeholdersTo detect the placeholder positions of a given text you can use the parse_placeholders() function:defparse_placeholders(text:str,open_ch:str='{',close_ch:str='}',escapes:bool=True)->Tuple[str,List[Tuple[int,int]]]:Wheretextis the text with placeholders to detect;open_chis the initial symbol of the placeholder andclose_chis the final one;escapesif True if you want that the escaped character '' should be escaped in the final returned text.
This function returns a tuple with the parsed text without escape characters,
and a list of positions with the initial and end position of each placeholder in that text.For example, if you have a text like the following:s='Some example of{term}\\{UN\\}'If you want to detect the {terms} but not {UN} because it is escaped with \, then you need to execute:fromplaceholderimportparse_placeholderss='Some example of{term}\\{UN\\}'parse_placeholders(s)Therefore, it will return the following results:('Some example of{term}{UN}',[(16,22)])Where, here, the placeholder is {terms}. The placeholder has to be delimited by just one character, but not more.
The placeholder delimiters can be changed by using the parametersopen_chandclose_ch:fromplaceholderimportparse_placeholderss='Some example of <term>{UN}'parse_placeholders(s,'<','>')The result will be similar, and now we do not need to escape the characters {} for {UN} because we have changed the
default delimiters:('Some example of <term>{UN}',[(16,22)])In this case the placeholder is <term>.Finally, you can detect the placeholders from a text without parse the escape characters changing the parameterescapes.If there are more than one placeholders, the results will be a list of positions.
For example:fromplaceholderimportparse_placeholderss='Some example of{term}{UN}'parse_placeholders(s)The output will be:('Some example of{term}{UN}',[(16,22),(23,27)])In this case, it detects both placeholders because the second one was not escaped with \.Replace text placeholdersWith this module you can replace the placeholders usingreplace_placeholders()orreplace_file_placeholders().
The first one is to work with a string value and the second one to replace in a text file.The syntax of thereplace_placeholders()function is:defreplace_placeholders(text:str,open_ch:str='{',close_ch:str='}',escapes:bool=True,**kwargs)->str:Wheretextis the text with placeholders to detect;open_chis the initial symbol of the placeholder andclose_chis the final one;escapesif True if you want that the escaped character '' should be escaped in the final returned text;
and, finally,kwargsare the value of the text placeholders.
The result of executing this functions will be the same string as the input but with the placeholders
replaced by they related values.
For example:fromplaceholderimportreplace_placeholderss='Some example of{term}\\{UN\\}'print(replace_placeholders(s,term='United Nations'))It will replace the placeholder '{term}' by the text "United Nations".
Therefore, the result will be:Some example of United Nations {UN}The syntax ofreplace_file_placeholders()is very similar:defreplace_file_placeholders(input_file:Union[str,PathLike,bytes],output_file:[str,PathLike,bytes],open_ch:str='{',close_ch:str='}',escapes:bool=True,**kwargs)->None:However, this function uses an input and output files instead a string.
For example, if we have the following test.txt file:This is a test with {num} placeholders to {action} the functions to parse \{placeholders\}.
Other line without placeholders.And we execute the following:fromplaceholderimportreplace_file_placeholdersreplace_file_placeholders('test.txt','test2.txt',num=2,action='test')This will generate a output file 'test2.txt' with the following content:This is a test with 2 placeholders to test the functions to parse {placeholders}.
Other line without placeholders.Check if there are placeholdersIt is possible to usehas_placeholders()function to check if a text has placeholders or not:defhas_placeholders(text:str,open_ch:str='{',close_ch:str='}')->bool:Wheretextis the text with placeholders to detect;open_chis the initial symbol of the placeholder andclose_chis the final one.
This function returns True if there is any placeholder delimited by those characters.
For example:fromplaceholderimporthas_placeholderss='Some example of{term}\\{UN\\}'has_placeholders(s)# Return Trues='Some example of{term}{UN}'has_placeholders(s)# Return Trues='Some example of\\{term\\}\\{UN\\}'has_placeholders(s)# Return Falses='Some example of term UN'has_placeholders(s)# Return FalseCount placeholdersCount the number of placeholders of a string.defnum_placeholders(text:str,open_ch:str='{',close_ch:str='}')->int:Wheretextis the text with placeholders to detect;open_chis the initial symbol of the placeholder andclose_chis the final one.
This function will return the number of detected placeholders delimited by those characters.
For example:fromplaceholderimportnum_placeholderss='Some example of{term}\\{UN\\}'num_placeholders(s)# Returns 1s='Some example of{term}{UN}'num_placeholders(s)# Returns 2s='Some example of\\{term\\}\\{UN\\}'num_placeholders(s)# Returns 0s='Some example of term UN'num_placeholders(s)# Returns 0Get the placeholder contentsWe have two functions to get the placeholder content:get_placeholders(),get_placeholder(),get_file_placeholders(),get_file_placeholder().
The first one obtains a list with all the placeholder values in the input string.
The second one get only one specific placeholder.
The other two functions are the equivalent ones but using a file text instead a string as input.The definition of the first is:defget_placeholders(text:str,open_ch:str='{',close_ch:str='}',type:Union[Callable,List[Callable]]=str)->List[Any]:Wheretextis the text with placeholders to detect;open_chis the initial symbol of the placeholder andclose_chis the final one;
andtypeis the type or types to convert the placeholder values.
This function returns a list of values with each placeholder value.
For example:fromplaceholderimportget_placeholderss='Some example of{term}\\{UN\\}'get_placeholders(s)# This returns ['term']s='Some example of{term}{UN}'get_placeholders(s)# This returns ['term', 'UN']s='Some example of{1}and{2}'get_placeholders(s)# This returns ['1', '2']get_placeholders(s,type=int)# This returns [1, 2]s='Some example of{1}and{term}'get_placeholders(s,type=[int,str])# This rturns [1, 'term']The functionget_placeholder()is very similar but only returns one placeholder.
By default, it returns the first one. Its syntax is:defget_placeholder(text:str,open_ch:str='{',close_ch:str='}',type:Callable=str,pos:int=0)->Any:Wheretype, in this case, has just one value andposis the position of the placeholder.
For example:fromplaceholderimportget_placeholders='Some example of{term}\\{UN\\}'get_placeholder(s)# This returns 'term's='Some example of{term}{UN}'get_placeholder(s)# This returns 'term'get_placeholder(s,pos=1)# This returns 'UN's='Some example of{1}and{2}'get_placeholder(s)# This returns '1'get_placeholder(s,type=int)# This returns 1get_placeholder(s,type=int,pos=1)# This returns 2The functionget_file_placeholders()andget_placeholder()have the following signature:defget_file_placeholders(file:Union[str,PathLike,bytes],open_ch:str='{',close_ch:str='}',type:Callable=str)->List[Any]:defget_file_placeholder(file:Union[str,PathLike,bytes],open_ch:str='{',close_ch:str='}',type:Callable=str,pos:int=0)->Any:Withfileto the file path instead of the string.
The first one return the list with the content of all the placeholders delimited by those characters, and
the other one returns only one placeholder in that position.
For example, if we have the following test.txt file:This is a test with {num} placeholders to {action} the functions to parse \{placeholders\}.
Other line without placeholders.We can execute the following:fromplaceholderimportget_file_placeholders,get_file_placeholderget_file_placeholders('test.txt')# Returns ['num', 'action']get_file_placeholder('test.txt')# Returns 'num'get_file_placeholder('test.txt',pos=0)# Returns 'num'get_file_placeholder('test.txt',pos=-1)# Returns 'action'