繁体   English   中英

自定义Python CSV分隔符

[英]Custom Python CSV delimiter

如何忽略双引号之间的逗号并删除不在双引号之间的逗号?

包括电池-只需使用Python随附的csv模块

例:

import csv

if __name__ == '__main__':
    file_path = r"/your/file/path/here.csv"
    file_handle = open(file_path, "r")
    csv_handle = csv.reader(file_handle)
    # Now you can work with the *values* in the csv file.

出于您的兴趣,您可以 (通常)使用正则表达式执行此操作;

mystr = 'No quotes,"Quotes",1.0,42,"String, with, quotes",1,2,3,"",,""'
import re
csv_field_regex = re.compile("""
(?:^|,)         # Lookbehind for start-of-string, or comma
(
    "[^"]*"     # If string is quoted: match everything up to next quote
    |
    [^,]*       # If string is unquoted: match everything up to the next comma
)
(?=$|,)         # Lookahead for end-of-string or comma
""", re.VERBOSE)

m = csv_field_regex.findall(mystr)

>>> pprint.pprint(m)
['No quotes',
 '"Quotes"',
 '1.0',
 '42',
 '"String, with, quotes"',
 '1',
 '2',
 '3',
 '""',
 '',
 '""']

这处理了除引号字符串内出现的转义引号之外的所有内容。 也可以处理这种情况,但是正则表达式变得更糟; 这就是为什么我们有csv模块的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM