[英]Removing quotes from text files
我需要讀取一個豎線(|)分隔的文本文件。 其中一個字段包含可能包含雙引號的描述。 我注意到所有包含“的行都在接收字典中丟失。為避免這種情況,我嘗試讀取整行,並使用 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 版
您可以使用正則表達式
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:
(...)
課程:方法 string.replace() 不會更改字符串本身。 修改后的文本必須存儲回來 (string = string.replace() )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.