【问题标题】:Filtering output in python?在python中过滤输出?
【发布时间】:2015-11-26 16:17:50
【问题描述】:

我有一个 python 脚本,它使用 mechanize 从网页中获取数据。这工作正常,但我已经完成了一项黑客工作,然后使用 bash 过滤我正在寻找的文本。我现在需要在主 python 脚本中执行此操作,因为我需要使用输出值。

response = br.submit()
print response.read()

这会打印出我然后用 bash 操作的响应

| grep usedData | cut -d '"' -f2 | sed 's/\<GB used\>//g'`

如何在 python 中完成这一切?

bash 脚本的输出将是一个数字(例如 123.45)

输入:

<tr><th>Current Data Usage:  </th><td>221.59GB</td></tr>


Output: 221.59

【问题讨论】:

标签: python


【解决方案1】:

试试这个:

input_html = "<tr><th>Current Data Usage:  </th><td>221.59GB</td></tr>"
begin = input_html.find("</th><td>")
end = input_html.find("GB</td>")
output = input_html[begin+len("</th><td>"):end]
print output

这应该可以准确找到您要查找的内容。

【讨论】:

  • 请不要使用str作为变量。如果这样做,您将无法使用str() 函数。
  • 很抱歉告诉你,但是input也是python中的一个函数;-)
  • 我也刚刚解决了这个问题 ;)
【解决方案2】:

您可以使用正则表达式查找“​​GB”之前的所有数字和句点序列。

>>> import re
>>> s = "<tr><th>Current Data Usage:  </th><td>221.59GB</td></tr>"
>>> match = re.search(r"([\d\.]*)GB", s)
>>> match.group(1)
'221.59'

【讨论】:

  • 非常感谢 - 我喜欢这个解决方案。似乎比我的 bash 脚本容易得多:)
猜你喜欢
  • 1970-01-01
  • 2020-05-02
  • 2019-10-05
  • 2022-01-10
  • 1970-01-01
  • 2014-06-15
  • 2016-04-26
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多