【问题标题】:Removing quotes from text files从文本文件中删除引号
【发布时间】:2018-03-11 07:32:19
【问题描述】:

我需要阅读一个以竖线(|)分隔的文本文件。 其中一个字段包含可能包含双引号的描述。 我注意到接收字典中缺少所有包含 " 的行。 为避免这种情况,我尝试读取整行,并使用 string.replace() 删除它们,如下所示,但看起来这些引号的存在在读行阶段会产生问题,即在字符串之前.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 版

【问题讨论】:

  • replace 不会就地替换。您必须将结果分配回变量:LI_text = LI_text.replace("|","/")
  • 这是由于“就地替换”问题。我将修改后的文本存储回变量中并且它起作用了。

标签: python


【解决方案1】:

你可以使用正则表达式

    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:
            (...)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 2014-05-05
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多