【问题标题】:why python adding \ to my file?为什么python将\添加到我的文件中?
【发布时间】:2014-12-10 10:04:41
【问题描述】:

我正在使用以下方法解析 xml 文件:

  lxml.etree.parse(xmlFile)  

我提取了一些包含单个反斜杠的节点属性 并将它们保存到字典中

然后我使用以下命令将字典写入文件:

f = open(myFile, 'w')
for k, v in sorted(dic.items()):
    f.write(str((k,v)))
    f.write('\n')
f.flush()
f.close()

知道问题是如果我在解析后将树写入文件使用:

     tree.write('output4.xml')

树与原始文件完全相同,但是 保存到 myFile 的字典有 \\ 而不是每个 \ 那么为什么 python 在它找到的地方添加 \。

示例: 这是原始属性:

"\displaystyle\mathbb{Z}_{n}\longrightarrow\mathbb{Z}"

在字典文件中变成:

'\\\displaystyle\\\mathbb{Z}_{n}\\\longrightarrow\\\mathbb{Z}'

【问题讨论】:

  • 它只是代表......

标签: python python-3.x dictionary


【解决方案1】:

str((k,v)) 使用kvrepr

>>> k = r'\textit{foo}'
>>> v = 'bla'
>>> s = str((k, v))
>>> s
"('\\\\textit{foo}', 'bla')"

这样做的好处是可以用ast.literal_eval 反序列化,因为来自repr 的转义字符串与Python 文字具有相同的语法:

>>> import ast
>>> print(ast.literal_eval(s)[0])

如果这不是您想要的,您将不得不找到其他写出配对的方法。

【讨论】:

  • 好的,这很好,它可以正确写入密钥但不写入值。我试图将其设为元组,但这会产生错误,它只能写 str
猜你喜欢
  • 2016-04-26
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2014-02-14
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
相关资源
最近更新 更多