Error “list indices must be integers or slices, not str” while looping

可紊 提交于 2021-02-10 14:15:53

问题


I'm trying to parse only the replies to my emails, which are stored in a CSV file. I am making use of this library which seems to be geared at doing that. My CSV columns look like this:

Date    From Name   From Address   To   Subject    Message

What I want to do is read the message column, perform the cleaning function which is EmailReplyParser.parse_reply(email_message) and replace it with the cleaned emails.

This is what I have right now:

from email_reply_parser import EmailReplyParser
import csv

with open('D:/Harry_Potter.csv', encoding="utf8") as inf:
    reader = csv.reader(inf.readlines())

with open('D:/clean.csv', 'w') as outf:
    writer = csv.writer(outf)
    for row in reader:
        EmailReplyParser.parse_reply(row['Message'])
    writer.writerows(reader)

This is the error I'm getting: TypeError: list indices must be integers or slices, not str.

How can I fix this?


回答1:


Your loop should be like this:

with open('D:/clean.csv', 'w') as outf:
    writer = csv.writer(outf)
    # need to skip the title
    title = reader.__next__()
    for row in reader:
        EmailReplyParser.parse_reply(row[0].split()[-1])
    writer.writerows(reader)


来源:https://stackoverflow.com/questions/65459205/error-list-indices-must-be-integers-or-slices-not-str-while-looping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!