0

I am trying to read a file with below data

Et1, Arista2, Ethernet1
Et2, Arista2, Ethernet2
Ma1, Arista2, Management1

I need to read the file replace Et with Ethernet and Ma with Management. At the end of them the digit should be the same. The actual output should be as follows

Ethernet1, Arista2, Ethernet1
Ethernet2, Arista2, Ethernet2
Management1, Arista2, Management1

I tried a code with Regular expressions, I am able to get to the point I can parse all Et1, Et2 and Ma1. But unable to replace them.

import re
with open('test.txt','r') as fin:
       for line in fin:
       data = re.findall(r'\A[A-Z][a-z]\Z\d[0-9]*', line)
       print(data)

The output looks like this..

['Et1'] 
['Et2'] 
['Ma1']

3 Answers 3

3
import re

#to avoid compile in each iteration
re_et = re.compile(r'^Et(\d+),')
re_ma = re.compile(r'^Ma(\d+),')

with open('test.txt') as fin:
    for line in fin:
        data = re_et.sub('Ethernet\g<1>,', line.strip())
        data = re_ma.sub('Management\g<1>,', data)
        print(data)
Sign up to request clarification or add additional context in comments.

Comments

1

This example follows Joseph Farah's suggestion

    import csv
    file_name = 'data.csv'
    output_file_name = "corrected_data.csv"

    data = []
    with open(file_name, "rb") as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:
            data.append(row)

    corrected_data = []
    for row in data:
        tmp_row = []
        for col in row:
            if 'Et' in col and not "Ethernet" in col:
                col = col.replace("Et", "Ethernet")
            elif 'Ma' in col and not "Management" in col:
                col = col.replace("Ma", "Management")
            tmp_row.append(col)
        corrected_data.append(tmp_row)

    with open(output_file_name, "wb") as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        for row in corrected_data:
            writer.writerow(row)        

    print data

Comments

0

Here are the steps you should take:

  1. Read each line in the file
  2. Separate each line into smaller list items using the comments as delimiters
  3. Use str.replace() to replace the characters with the words you want; keep in mind that anything that says "Et" (including the beginning of the word "ethernet") will be replaced, so remember to account for that. Same goes for Ma and Management.
  4. Roll it back into one big list and put it back in the file with file.write(). You may have to overwrite the original file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.