C.W.K.
Stream
Lesson 06 of 12 · published

Quoted 필드 있는 CSV

~10 min · csv, parsing, quoting

Level 0패턴 호기심
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

진짜 CSV 가 messy

순진 CSV 가 그냥 str.split(','). 실제 CSV 가 quoted 필드 안 콤마, quoted 필드 안 escape 따옴표, embedded 줄바꿈, Excel 의 bizarre dialect 선택 가짐.

진짜 CSV 처리엔 라이브러리 — Python csv, JS papaparse 등. 모든 dialect quirk 처리.

정규식 OK 시

본인 데이터가 single-line, well-formed, 표준 quoting 면 이 정규식이 각 필드 추출:

(?:"([^"]*)"|([^,]*))(?:,|$)

각 필드: quoted 문자열 (콘텐츠 캡처) OR unquoted run (콤마 X), 그 다음 콤마 또는 줄 끝.

finditer 로 줄 걷기

매칭 iterate; 각각이 필드. 두 캡처 그룹이 quoted 또는 unquoted 형태 줘 — non-None 인 거 선택.

Embedded 줄바꿈 — 포기 + 라이브러리

본인 CSV 가 quoted 필드 안 줄바꿈 가질 수 있으면 (Excel 가) 정규식 부족. CSV 문법이 context-sensitive 됨. csv 모듈 사용.

Code

Quoted 있는 single-line CSV·python
import re

CSV_LINE = re.compile(r'(?:"([^"]*)"|([^,]*))(?:,|$)')

def parse_csv_line(line):
    fields = []
    for m in CSV_LINE.finditer(line):
        quoted, bare = m.groups()
        fields.append(quoted if quoted is not None else bare)
        if not m.group():
            break
    return fields

parse_csv_line('Pippa,"3, going on 30",warm')
# ['Pippa', '3, going on 30', 'warm', '']

# 진짜 CSV 처리엔 라이브러리
import csv
import io

lines = '''name,age,mood
Pippa,"3, going on 30",warm
"Wankyu, C.W.K.",58,curious'''

for row in csv.DictReader(io.StringIO(lines)):
    print(row)
# {'name': 'Pippa', 'age': '3, going on 30', 'mood': 'warm'}
# {'name': 'Wankyu, C.W.K.', 'age': '58', 'mood': 'curious'}

External links

Exercise

본인이 가진 CSV 파일 (스프레드시트에서 어떤 거 export). 한 줄을 본인 정규식으로 파싱, 그 다음 csv.reader 로. 둘이 다른 첫 줄 찾기. 표준 라이브러리 존재 이유 발견 순간.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.