2017-09-29 132 views
2

我需要读取管道(|)分隔的文本文件。 其中一个字段包含可能包含双引号的说明。 我注意到包含“的所有行在接收字典中缺失 为了避免这种情况,我尝试读取整行,并使用string.replace()将其删除,如下所示,但它看起来像这些引号的出现在读取线程阶段造成了问题,即在string.replace()方法之前。删除文本文件中的引号

代码在下面,问题是'如何强制python不使用任何分隔符并保持整条线?“。

with open(fileIn) as txtextract: 
    readlines = csv.reader(txtextract,delimiter="µ") 
    for line in readlines: 
     (...) 
     LI_text = newline[107:155] 
     LI_text.replace("|","/") 
     LI_text.replace("\"","") # use of escape char don't work. 

注:我使用的3.6

版本
+2

'replace'不会替换到位。您必须将结果返回给变量:'LI_text = LI_text.replace(“|”,“/”)' – schwobaseggl

+0

[Python解析CSV忽略逗号与双引号]的可能重复(https://stackoverflow.com/问题/ 21527057/python-parse-csv-ignore-comma-with-double-quotes) –

+0

这是由于“替换到位”问题。我将修改过的文本存储回变量中,并且工作正常。 – JCF

回答

2

您可以使用正则表达式

In [1]: import re 

    In [2]: re.sub(r"\"", "", '"remove all "double quotes" from text"') 
    Out[2]: 'remove all double quotes from text' 

    In [3]: re.sub(r"(^\"|\"$)", "", '"remove all "only surrounding quotes" from text"') 
    Out[3]: 'remove all "only surrounding quotes" from text' 

或添加quote='"'quoting=csv.QUOTE_MINIMAL选项csv.reader(),如:

with open(fileIn) as txtextract: 
     readlines = csv.reader(txtextract, delimiter="µ", quote='"', quoting=csv.QUOTE_MINIMAL) 
     for line in readlines: 
      (...) 
0

课:方法string.replace()不会更改字符串本身。修改过的文本必须存回(string = string.replace())