Question

I'm forced to turn from Perl to Python now, took a course even. But I'm struggling already with a simple data cleaning task on CSV files. I want to replace a ¶ by a SPACE in a specific column, the other columns must be untouched:

In Perl this is very straight forward and works like a charm:

perl -F";" -lane 'BEGIN {$,=";"} print $F[0],$F[1],$F[2],$F[3],$F[4],$F[5],$F[6],$F[7],$F[8],$F[9],$F[10],$F[11], $F[12]=~s/\¶/ /g, $F[13]' a.csv

How could I do that in Python? It doesn't need to be a oneliner...

Était-ce utile?

La solution

It could be done in one line (but it would be hard to understand). Here's a slightly more verbose example.

import io
import re

with io.open('a.csv') as fin:
    for line in fin:
        parts = line.split(';')
        parts[13] = parts[13].replace('¶', ' ')
        print ','.join(parts)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top