Home > Software engineering >  replace specific values in a list with another python
replace specific values in a list with another python

Time:06-22

I've imported a long csv file into a list in my python file and am trying to format it into a way that splunk can read each line as

node,building,ap,something

while a example line right now looks like

mkc2-rap,Top > RAPs > Rhodes Node > 7240 - Rhodes Hall

what i would like to do is remove the spaces and replace all ">" & "-" with a ","

heres my code right now '''

import csv

import re

with open('airwavenorth.csv', newline='') as f:
    reader = csv.reader(f)
    airwavenorth = list(reader)

for i in range(len(airwavenorth)):
    if airwave[i] == '>':
        airwavenorth[i] = ','

CodePudding user response:

it can be done by using .replace(), first you would have to convert your list to a string.

list1 = [1,2,3]
str1 = ''.join(str(e) for e in list1)

then simply using

l = "mkc2-rap,Top > RAPs > Rhodes Node > 7240 - Rhodes Hall"

l = l.replace(">", ",")
l = l.replace("-", ",")

print(l)
#mkc2,rap,Top , RAPs , Rhodes Node , 7240 , Rhodes Hall

CodePudding user response:

import re

sample = ['mkc2-rap', 'Top > RAPs > Rhodes Node > 7240 - Rhodes Hall']

for i in range(len(sample)):
    sample[i] = re.sub('>|-', ',', sample[i])
    sample[i] = re.sub(' ', '', sample[i])
    
>>> print(sample)
>>> ['mkc2,rap', 'Top,RAPs,RhodesNode,7240,RhodesHall']

CodePudding user response:

import csv

# Read in the CSV file
with open('test.csv', 'r') as csvfile:
    # Split the data on commas
    data = csv.reader(csvfile, delimiter='\n')
    # Create an empty list to hold the data
    data_list = []
    # Loop through the data
    for row in data:
        # Append the data to the list
        data_list.append(row)


# Print the list
# print(data_list[0])
# print(type(data_list[0]))

# covert list to string
for i in range(len(data_list)):
    data_list[i] = str(data_list[i])

new_list = []
for i in range(len(data_list)):
    # remove space 
    x = data_list[i].replace(' ', '')
    # remove brackets
    x = x.replace('>', ',')
    # remove -
    x = x.replace('-', ',')
    # print(x)
    new_list.append(x)

print("Before: ", data_list[0])
print("After: ", new_list[0])

>>> Before:  ['mkc2-rap,Top > RAPs > Rhodes Node > 7240 - Rhodes Hall']
>>> After:  ['mkc2,rap,Top,RAPs,RhodesNode,7240,RhodesHall']


  • Related