【问题标题】:Python: How to remove all quotations from a text file?Python:如何从文本文件中删除所有引号?
【发布时间】:2017-04-21 09:57:51
【问题描述】:

我有一个文本文件,其中包含'" 形式的引用。该文本文件的格式为。

"string1", "string2", 'string3', 'string4', ''string5'', etc. 

如何删除所有引用 '" 而将文件的其余部分保持原样?

我怀疑应该是这样的:

with open('input.txt', 'r') as f, open('output.txt', 'w') as fo:
    for line in f:
        fo.write(line.strip())

line.strip() 以某种方式剥离了引号的字符串。还需要什么吗?

【问题讨论】:

  • 我会使用生成器表达式来过滤掉引号:''.join(c for c in line if c not in '"\'')
  • 可能重复:stackoverflow.com/questions/22187233/…ShanZhengYang,如果这回答了您的问题,请告诉我们。
  • 你可以使用replace(),但我想知道这些引号是怎么来的。我希望你不要将 python 对象写入文本文件,你应该使用 pickle 或类似的代替
  • @Robᵩ replace() 的问题在于,如下实现,它还删除了括号

标签: python text


【解决方案1】:

你已经接近了。而不是str.strip(),试试str.replace()

with open('input.txt', 'r') as f, open('output.txt', 'w') as fo:
    for line in f:
        fo.write(line.replace('"', '').replace("'", ""))

【讨论】:

  • 恕我直言,@ShanZhengYang,我不相信你。我发布的代码中没有任何内容删除括号。
  • 查看文本文件,不幸的是我犯了一个错误。上面删了。括号还在。但是,有几个引用仍然存在,尤其是附近的括号("string1", "string2", "string3", "string4")
  • 再次,尊敬的,我不相信你。你能提供一个单行的input.txt 文件,当交给上面的三行程序时,它的行为方式是这样的吗?
  • 对于这种行为,最好查看整个文本文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 2014-02-24
相关资源
最近更新 更多