本文介绍了python中的sscanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找Python中的sscanf()等效项.我想解析C中的/proc/net/*文件,我可以做这样的事情:

I'm looking for an equivalent to sscanf() in Python. I want to parse /proc/net/* files, in C I could do something like this:

int matches = sscanf(
        buffer,
        "%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",
        local_addr, &local_port, rem_addr, &rem_port, &inode);

我起初以为使用str.split,但是它不会在给定的字符上分开,而是整个sep字符串:

I thought at first to use str.split, however it doesn't split on the given characters, but the sep string as a whole:

>>> lines = open("/proc/net/dev").readlines()
>>> for l in lines[2:]:
>>>     cols = l.split(string.whitespace + ":")
>>>     print len(cols)
1

如上所述,哪个应该返回17.

Which should be returning 17, as explained above.

是否有与sscanf等效的Python(不是RE),还是标准库中的字符串拆分功能,可以对我不知道的任何字符范围进行拆分?

Is there a Python equivalent to sscanf (not RE), or a string splitting function in the standard library that splits on any of a range of characters that I'm not aware of?

推荐答案

Python没有内置的sscanf等效项,在大多数情况下,通过工作解析输入实际上更有意义直接使用字符串,使用正则表达式或使用解析工具.

Python doesn't have an sscanf equivalent built-in, and most of the time it actually makes a whole lot more sense to parse the input by working with the string directly, using regexps, or using a parsing tool.

人们可能已经实现了sscanf,对翻译C最为有用,例如在以下模块中: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/

Probably mostly useful for translating C, people have implemented sscanf, such as in this module: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/

在这种特殊情况下,如果您只想基于多个拆分字符拆分数据,则re.split确实是正确的工具.

In this particular case if you just want to split the data based on multiple split characters, re.split is really the right tool.

这篇关于python中的sscanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 21:07