如何忽略双引号之间的逗号并删除不在双引号之间的逗号?
包括电池 - 只需使用 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
模块的原因。