Python 中的 sscanf [英] sscanf in Python

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

问题描述

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

int 匹配 = sscanf(缓冲,"%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X%*X %*d %*d %ld %*512s
",local_addr, &local_port, rem_addr, &rem_port, &inode);

我一开始想使用 str.split,但它不会在给定的字符上拆分,而是将 sep 字符串作为一个整体:

<预><代码>>>>lines = open("/proc/net/dev").readlines()>>>对于行 [2:] 中的 l:>>>cols = l.split(string.whitespace + ":")>>>打印 len(cols)1

应该返回 17,如上所述.

是否有等效于 sscanf(不是 RE)的 Python,或者标准库中的字符串拆分函数,可以拆分我不知道的任何字符范围?

解决方案

Python 没有 sscanf 等效的内置,而且大多数时候它实际上更有意义通过直接处理字符串、使用正则表达式或使用解析工具来解析输入.

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

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

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
",
        local_addr, &local_port, rem_addr, &rem_port, &inode);

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

Which should be returning 17, as explained above.

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 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.

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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