0

I created an CSV file as a sample where I have @handles. (Twitter handles) For privacy reasons I need to remove each handle - for example @johnny, @rose, @lucy.

This is what I have so far..... but I'd like to replace the whole handle on each line with an x.

file = open('./ExcelTest.csv', 'r')
for line in file:
    #temp = line.find("@")
    line.replace("@"," ")
    print(line)

Please help! THANKS SO MUCH!

2 Answers 2

1

Regex would certainly help here. Loop through each line and use re.sub to get rid of those handles.

import re

...    
new_line = re.sub('@[\S]+', '', line)
....

Example:

In [65]: line = "help me @lucy I'm drowning"

In [66]: re.sub('@[\S]+', '', line)
Out[66]: "help me  I'm drowning"

Now, there's that matter of the extra space... hmm... you can chain re.sub calls like this:

new_line = re.sub('[\s]+', ' ', re.sub('@[\S]+', '', line)) 

This is only assuming you don't want extra spaces clustering together once you void the handles.

Sign up to request clarification or add additional context in comments.

Comments

1

If your csv file contains all the twitter handles in the same row you may want to use Python's built in csv module. The csv module will allow you to read in each row as a Python list and you can simply del elements of the list at a particular index. You can then write back the output to a new file.

import csv

file_handler = open('./ExcelTest.csv','r')
file_handler_write = open('./ExcelTest_New.csv','w')

csv_reader = csv.reader(file_handler,delimiter=',')
csv_writer = csv.writer(file_handler_write,delimiter=',')


twitter_handle_col = 2 # set the twitter handle column here

for line in csv_reader:
    del line[twitter_handle_col]
    csv_writer.writerow(line)

file_handler_write.close()
file_handler.close()

The columns and delimiters may differ in your particular case but this may be the simplest approach if using a csv.

Input - ExcelTest.csv:

a,b,c,d
b,c,d,a
d,c,b,a

Output - ExcelTest_New.csv:

a,b,d
b,c,a
d,c,a

Notice that the third column was deleted.

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.