replace a set of strings in a .txt file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Derick yap
    New Member
    • Feb 2012
    • 1

    replace a set of strings in a .txt file

    hi everyone,

    My problem goes like this (*.d) which can be opened using wordpad.
    Now I need to replace some strings inside my file which is enclosed within double quotes.
    I have to use a I/P file as a text delimited file which have two columns first column old string and the second one is new string.
    As Im new to python language can some one help me how to start with it..?

    Thanks in advance.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Create a dictionary from the file with 2 columns.
    Code:
    dd = {"Col 1 text 1": "Col 2 text 1", "Col 1 text 2": "Col 2 text 2"}
    I might approach replacing the text like this:
    Code:
    >>> import re
    >>> text = 'A line in text file containing "Col 1 text 1"'
    >>> dd = {"Col 1 text 1": "Col 2 text 1", "Col 1 text 2": "Col 2 text 2"}
    >>> patt = re.compile(r'"(.+)"')
    >>> m = patt.search(text)
    >>> if m and m.group(1) in dd:
    ... 	text = text.replace(m.group(1), dd[m.group(1)])
    ... 	
    >>> text
    'A line in text file containing "Col 2 text 1"'
    >>>

    Comment

    Working...