Fiki Firmansyah
Fiki Firmansyah

Reputation: 11

How to fix AttributeError: 'list' object has no attribute 'replace' when I try to replace some text in a csv read

I try to replace a text in csv read with some data dictionary, but I got an Error.

import csv

dataset = open('../sentimenprabowo.csv', 'r')
sentiment = csv.reader(dataset, delimiter=',')

newDok = open('../sentimenprabowopreproses.csv', 'w')
save = csv.writer(newDok)

data= open("convertcsv.json", "r")
APPOSTOPHES=data.read()

new_sentence = []
for row in sentiment:     
    print(row)
    for candidate_replacement in APPOSTOPHES:                
        if candidate_replacement in row:            
            #print(candidate_replacement)
            row = row.replace(candidate_replacement, APPOSTOPHES[candidate_replacement])
    new_sentence.append(row)
rfrm = "".join(new_sentence)
print(rfrm)

I hope this can be replace all the text in my csv who same text with data dictionary (correction spelling).

but the result is error:

  File "readdata.py", line 45, in <module>
    row = row.replace(candidate_replacement, APPOSTOPHES[candidate_replacement])
AttributeError: 'list' object has no attribute 'replace'

help me please...

this is my convertcsv.json file:

{"@":"di","ababil":"abg labil","abis":"habis","acc":"accord","ad":"ada","adlah":"adalah"}

Upvotes: 1

Views: 15144

Answers (2)

Shahin Shemshian
Shahin Shemshian

Reputation: 376

As the error says your row is a list and doesn't have replace method. You can convert it to string replace as you wish then again cast to array:

row = str(row).replace(candidate_replacement, APPOSTOPHES[candidate_replacement]).split(',')

Upvotes: 3

Alif Jahan
Alif Jahan

Reputation: 795

You can do this with list comparison

use this

for r in range(len(row)):
    if row[r] == candidate_replacement:
        row[r] = APPOSTOPHES[candidate_replacement]

Upvotes: 1

Related Questions