我有一个简单的问题,python交换引号类型(单和双)自动。 因此,我无法回到原始文本。
这是一个例子
s1 = ('foo\'bar' , 'bar\"foo', 'dead\'\"beef', 'beef\\\'\"dead') s2 = unicode(s1) print repr(s2) >>>u'("foo\'bar", \'bar"foo\', \'dead\\\'"beef\', \'beef\\\\\\\'"dead\')'在这个例子中,python为元组的第一个元素进行了引号类型的自动交换。 当然这是预期的,因为字符串中只出现单引号。 我遇到的问题是我正在尝试读取一个格式与上面打印值完全相同的文件,包括u,起始引号和尾随引号。 有没有办法读取文件并返回原始的s1元组。 实际上,我甚至不需要元组里面的字符串。 没有编码/解码方案我发现因为自动交换而正常工作。 当然我可以写一个正则表达式或函数来解决这个问题,但必须有一个python方式来做到这一点。 酸洗或任何其他序列化也不适合我。
提前致谢
I am having a simple issue with python swapping quotes types (single and double) on me automatically. Because of it I can't get back to the original text.
Here is an example
s1 = ('foo\'bar' , 'bar\"foo', 'dead\'\"beef', 'beef\\\'\"dead') s2 = unicode(s1) print repr(s2) >>>u'("foo\'bar", \'bar"foo\', \'dead\\\'"beef\', \'beef\\\\\\\'"dead\')'In this example python did an auto-swap of quote types for the first element of the tuple. Of course this was expected since only single quotes appeared in the string. The issue I have is I am trying to read a file which is of the format exactly like the printed value above including the u, starting quote, and trailing quote. Is there a way to read the file and return back to the original s1 tuple. Actually, I don't even need the tuple just the strings inside. No encoding/decoding scheme I have found works properly because of the auto-swapping. Of course I can write a regex or function to solve this but there must be a python way of doing this. Also pickling or any other serialization is not a solution for me.
thanks in advance
最满意答案
暂时搁置报价问题,让我们专注于您的真正需求:
读取一个格式与上面打印值完全相同的文件,包括u,起始引号和尾随引号。 ......实际上,我甚至不需要元组里面的字符串
如果你有一个文件,其内容如下:
u'("foo\'bar", \'bar"foo\', \'dead\\\'"beef\', \'beef\\\\\\\'"dead\')'以下程序将允许您访问内部的字符串:
import ast with open('x.txt') as input_file: for line in input_file: strings = ast.literal_eval(ast.literal_eval(line)) # You can do whatever you want with the `strings` var, e.g: assert(strings[0] == "foo'bar") assert(strings[0] == 'foo\'bar') print strings[0]参考:
https://docs.python.org/2/library/ast.html#ast.literal_evalSetting aside the issue of quotes for a moment, let's concentrate on your real need:
to read a file which is of the format exactly like the printed value above including the u, starting quote, and trailing quote. ... Actually, I don't even need the tuple just the strings inside
If you have a file, the contents of which look like so:
u'("foo\'bar", \'bar"foo\', \'dead\\\'"beef\', \'beef\\\\\\\'"dead\')'The following program will give you access to the strings inside:
import ast with open('x.txt') as input_file: for line in input_file: strings = ast.literal_eval(ast.literal_eval(line)) # You can do whatever you want with the `strings` var, e.g: assert(strings[0] == "foo'bar") assert(strings[0] == 'foo\'bar') print strings[0]Reference:
https://docs.python.org/2/library/ast.html#ast.literal_eval
更多推荐
发布评论