如何从python中的命令行接收正则表达式 [英] how to receive regex from command line in python

查看:137
本文介绍了如何从python中的命令行接收正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从命令行
接收类似'\t'(制表符)的分隔符,并使用它来解析文本文件。

I want to receive a delimiter like '\t' (tab) from command line, and use it to parse a text file.

如果我输入

delimiter = sys.argv[1]

在代码中,然后从命令行键入

in the code, and type from the command line

$ python mycode.py "\t"

分隔符为'\\ t',即python会按原样保留输入字符串。

delimiter is '\\t' i.e., python does its thing to preserve input string as is.

我想将其转换为'\t',以便我可以使用例如

I want to convert this to '\t' so that I can use e.g.,

'a\tb\tc'.split(delimiter)

以获得 ['a','b','c']

我尝试将'\'转换为'\',但失败了。

I've tried to convert '\' to '\', but failed.

推荐答案

在Python 2中,您可以使用 str.decode('string_escape')

In Python 2 you can use str.decode('string_escape'):

>>> '\\t'.decode('string_escape')
'\t'

在Python 3中,您必须先将字符串编码为字节,然后使用 unicode_escape

In Python 3 you have to encode the string to bytes first and then use unicode_escape:

>>> '\\t'.encode().decode('unicode_escape')
'\t'

这两个解决方案都接受任何转义序列并将其正确解码,因此您甚至可以使用一些花哨的unicode东西:

Both solutions accept any escape sequence and will decode them correctly, so you could even use some fancy unicode stuff:

>>> '\\t\\n\\u2665'.encode().decode('unicode_escape')
'\t\n♥'

这篇关于如何从python中的命令行接收正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆