Search code examples
pythontext

Python Library to Substitute Some Texts in a Big Text File


Using Python 3.10 on Ubuntu 22.04.

Here is the scenario. There is a large text file called raw.txt stored locally with some parameterised text. A small example would be like

This letter serves to confirm the employment of {full_name} at {company_name}, at {city_name} with a compensation of {salary} per {period}. 

and in the python script, I have the corresponding variables, like

full_name:str='John Smith'
company_name:str='Glaxo Inc.'
city_name:str='Houston'
salary:int=8500
period:str='month'

So what would be the cleanest way to substitute the parameters with the actual variables.

I hope I am describing the problem clearly, basically, something akin to frontend template rendering, but all inside python, loading the raw.txt from a disk file, and generating the output string. I could probably use the f string feature of python, but somehow it does seem a bit clunky. The function signature would be

def text_from_template(raw_text:os.PathLike, 
                        params:Dict[str, Any])->str:
    """Generate the new string based on the template file and dictionary."""
    raise NotImplementedError

Note that I am the author of raw.txt as well, which means if the template format I showed (used just for demonstration) is not correct/clean, I can rewrite it, but this is the use case.

I can use some third party library from pip, if necessary, with the constraints that

  • Free and open source
  • Well maintained
  • Works on both Ubuntu and windows

Solution

  • Why not just use python's str.format():

    s = "This letter serves to confirm the employment of {full_name} at {company_name}, at {city_name} with a compensation of {salary} per {period}."
    
    v = {
        "full_name":'John Smith',
        "company_name":'Glaxo Inc.',
        "city_name":'Houston',
        "salary":8500,
        "period":'month'
    }
    
    s.format(**v)
    # 'This letter serves to confirm the employment of John Smith at Glaxo Inc., at Houston with a compensation of 8500 per month.'
    

    Your strings works as-is. You just need to put your variables in a dict or other mapping.