0

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

4

2 回答 2

3

包括电池 - 只需使用 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.
于 2012-05-12T02:35:45.103 回答
1

只是为了您的兴趣,您可以(大部分)使用正则表达式来执行此操作;

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模块的原因。

于 2012-05-12T05:34:11.003 回答