A家经典题型 CSV parser

2019-04-08  本文已影响0人  jl先生

把一个字符串转换成CSV格式。
输入:

Input: csvformat
John,Smith,john.smith@gmail.com,Los Angeles,1
Jane,Roberts,janer@msn.com,"San Francisco, CA",0
"Alexandra ""Alex""",Menendez,alex.menendez@gmail.com,Miami,1 """Alexandra Alex"""

输出:

Output: escaped string
John|Smith|john.smith@gmail.com|Los Angeles|1
Jane|Roberts|janer@msn.com|San Francisco, CA|0
Alexandra "Alex"|Menendez|alex.menendez@gmail.com|Miami|1 "Alexandra Alex"

关键在于处理好状态转移的关系

def parsecvs(str):
    res = []
    tmp = ""
    isQuote = False
    for i in range(len(str)):
        if isQuote: #""引号内的字符
            if str[i] == "\"":
                if i + 1 < len(str) and str[i + 1] == "\"": #两个都是" 转转义一个"
                    tmp += "\""
                else: #引号匹配成功,弹出
                    isQuote = False
            else:
                tmp += str[i]
        else:
            if str[i] == ",": #碰到逗号就算一个cvs单位
                res.append(tmp)
                tmp = ""
            elif str[i] == "\"": #进入引号内
                isQuote = True
            else:
                tmp += str[i]
    res.append(tmp)
    return "|".join(res)

import sys
while True:
    line1 = sys.stdin.readline().strip('\n')#.strip().split()
    str = str(line1)
    res = parsecvs(str)
    print(res)

结果展示


image.png
上一篇下一篇

猜你喜欢

热点阅读