Home > Mobile >  String matching and replace
String matching and replace

Time:02-05

I have a text file like this and i want in implement in python

Enter the Username"<Username>" and phonenumber"<phonenumber>"
Enter the origin"<origin>" and destination"<destination>"
Examples:
 | Username | phonenumber | origin | destination|
 | JOHN | 40256786 | NYC | LONDON |

i want to replace the string which are in <> and replace with actual data, and my output will look like this :

Enter the Username "JOHN" and phonenumber "40256786"
Enter the origin "NYC" and destination "LONDON"

CodePudding user response:

One way would be to split each line by the delimiting character |. Then you can set the variables for the string accordingly.

sample_line = '| JOHN | 40256786 | NYC | LONDON |'
sample_line = sample_line.split('|')

data = {
    'Username':     sample_line[1],
    'phonenumber':  sample_line[2],
    'origin':       sample_line[3],
    'destination':  sample_line[4]
    }

text = '''\
Enter the Username "{Username}" and phonenumber "{phonenumber}"
Enter the origin "{origin}" and destination "{destination}"\
'''

print(text.format(**data))

Alternatively, you should be able to use something like csv.reader

CodePudding user response:

Update

Try:

import re

text = []
data = []
with open('data.txt') as fp:
    line = ''
    for line in fp:
        if line.startswith('Examples'):
            break
        text.append(line)
    text = ''.join(text)
    headers = re.split('\s*\|\s*', fp.readline())[1:-1]
    for line in fp:
        values = re.split('\s*\|\s*', line)[1:-1]
        data.append(dict(zip(headers, values)))

for d in data:
    print(re.sub(r'\<(?P<key>[^>]*)\>', lambda x: d[x.group('key')], text))

Output:

Enter the Username"JOHN" and phonenumber"40256786"
Enter the origin"NYC" and destination"LONDON"

Old answer

You can use plenty of text processors to substitute text by variables: string.Template ($), format strings ({ }), Jinja2 ({{ }}). If you can, change your delimiter:

Here an example of format strings:

text = '''\
Enter the Username "{Username}" and phonenumber "{phonenumber}"
Enter the origin "{origin}" and destination "{destination}"\
'''

data = {'Username': 'John', 'phonenumber': '40256786',
        'origin': 'NYC', 'destination': 'LONDON'}

print(text.format(**data))

Output:

Enter the Username "John" and phonenumber "40256786"
Enter the origin "NYC" and destination "LONDON"
  •  Tags:  
  • Related