Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
引号异常中转义引号的Python异常_Python_Regex_Csv - Fatal编程技术网

引号异常中转义引号的Python异常

引号异常中转义引号的Python异常,python,regex,csv,Python,Regex,Csv,我想将csv从逗号分隔改为制表符分隔。引号之间也有逗号,所以我需要一个例外。所以,谷歌搜索和stackoverflow给我带来了: import re f1 = open('query_result.csv', 'r') f2 = open('query_result_tab_separated.csv', 'w') for line in f1: line = re.sub(',(?=(([^\"]*\"){2})*[^\"]*$)(?![^\[]*\])', '\t', line)

我想将csv从逗号分隔改为制表符分隔。引号之间也有逗号,所以我需要一个例外。所以,谷歌搜索和stackoverflow给我带来了:

import re
f1 = open('query_result.csv', 'r')
f2 = open('query_result_tab_separated.csv', 'w')
for line in f1:
    line = re.sub(',(?=(([^\"]*\"){2})*[^\"]*$)(?![^\[]*\])', '\t', line)
f2.write(line)
f1.close()
但是,在引号之间,我还可以找到转义引号\“。一行示例:

"01-003412467812","Drontmann B.V.",1,6420,"Expert in \"Social, Life and Tech Sciences\""

我当前的代码将Social后面的逗号也更改为一个选项卡,但我不希望这样。我如何才能为引号以及在该例外和转义引号例外中创建一个例外?

您不能使用regexp执行此操作

Python有一个
csv
模块,用于执行以下操作:

import csv
with open('test.csv', 'rb') as csvfile:
    data = csv.reader(csvfile, delimiter=',', quotechar='"', escapechar='\\')
    for row in data:
        print ' | '.join(row)
模块可以处理此问题。您可以设置转义字符,并指定如何使用和转义字段中的引号:

这将创建一个新的以制表符分隔的文件,该文件在原始文件的字段中保留逗号和转义引号。或者,默认设置将使用
“”
(双引号)转义引号:

w = csv.writer(outfile, delimiter='\t')
这将写入如下数据:

01-003412467812 Drontmann B.V. 1 6420 "Expert in ""Social, Life and Tech Sciences""" 01-003412467812 Drontmann B.V.1 6420“社会、生命和技术科学专家”
使用stdlib的
csv
模块(用于读写),它知道如何解决这个问题。这很难。引号之间的东西不再是“正则表达式”“因为这是一种不规则的模式。使用csv解析器,例如
csv
pandas.read_csv
。可能是这样的:?该死,我读了文档,我试过了,但没有使用两个斜杠(之后我想到了regex)。谢谢 01-003412467812 Drontmann B.V. 1 6420 "Expert in ""Social, Life and Tech Sciences"""