0

I'm fairly new to python and I have a task where I have to import some addresses from a text file and then search for and abbreveate the title for the road (i.e change 'road' to 'RD').

So far I've managed to import the file and I've been able to form a 2D array where the whole address is in a seperate array inside the main array. I've been looking for a way to get inside the arrays so I can split the strings them so I can do the abbreveation and then output each sub array on its own line in excel.

This is my code at the moment:

def sec_2():
    addresses = [] 
    with open('Addresses2.txt', newline='') as Addresses2: 
        for row in csv.reader(Addresses2): 
            addresses.append(row)
    print(addresses) 

The code outputs this so far:

[['52 Corinthian Road', ' First Floor'], ['20 Ingram Street', ' Forest Hills', ' New York'], ['14 Westbourne Terrace Road', ' Buxton'], ['The Terrace Restaurant', ' 81 Royal Street', ' Solihull']]

I need it to be:

[['52', 'Corinthian', 'Road', ' First', 'Floor']], [['20', 'Ingram', 'Street', ' Forest', 'Hills', 'New', 'York'] etc...

3
  • Perhaps use addresses.append(row.split()) instead of trying to split the rows after the fact. Commented Sep 4, 2017 at 16:20
  • [['52', 'Corinthian', 'Road', ' First', 'Floor']] is this your requirement or a typo? Doesn't really seem to serve any purpose. Or do you mean to say [['52', 'Corinthian', 'Road', ' First', 'Floor'],['20', 'Ingram', 'Street', ' Forest', 'Hills', 'New', 'York']] Commented Sep 4, 2017 at 16:21
  • That was a typo, sorry. Also, I tried 'addresses.append(row.split())'and it didn't work. Commented Sep 6, 2017 at 10:19

2 Answers 2

1

You should use the str.split function for each string in your list.

split_strings = []
for string in string_list:
    split_strings.append(string.split(' '))
Sign up to request clarification or add additional context in comments.

Comments

0

You can use itertools:

import csv
import itertools

data = csv.reader(open('filename.csv'))
final_data = [list(itertools.chain.from_iterable([b.split() for b in i])) for i in data]

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.