Search code examples
pythoncapitalize

Capitalize first letter of each word between [ and ] in text file


EDIT: This question is different from other "capitalize first letter" questions because it requires capitalization only between "[" and "]". Since the title was incomplete, I have edited it.

I have a text file in which I need to reformat the text.

I have tried to loop lines and words while the file is open in 'r+', but have been unsuccessful.

Here is a sample:

Create Table Data(
    [SOME ID] int,
    [LAST NAME] varchar(30),
    [FIRST NAME] varchar(30),
    [TLA THING] smallint,
    [TLA THING REMARK] varchar(255)
)

I would like the first letter in each word between the [ ] to be capitalized. And as a bonus I'd love spaces between [ ] to be replaced with underscores.

code I tried:

f = open('somescript.sql','r+')
for line in f:
    for word in line:
        word.capitalize()

I also tried f.write(word.capitalize()) instead of just word.capitalize. All results were equally tragic.


Solution

  • The way I would code this :

    1. load the whole content of your file
    2. use the module re (re.sub would help) to transform parts that need to be
    3. overwrite the file with the transformed text

    The implementation :

    txt = # load your file
    pattern = re.compile(r"\[(.*)\]")
    transform = lambda mo : mo.group(0).title().replace(" ", "_")
    new_txt = pattern.sub(transform, txt)
    # write new text