【问题标题】:Find patterns in a string in Python and printing在 Python 中查找字符串中的模式并打印
【发布时间】:2021-07-20 01:34:46
【问题描述】:

所以我在 python 中有以下字符串变量:pytest_summary

其内容为:“1失败,316通过,204警告,0跳过,0 xfailed in 40.82s”

我需要一种方法来查找字符串中的特定模式,例如“通过”,然后将其前面的数字(即 316)保存到变量中。我曾经使用 awk 或 sed 来做到这一点,这更容易和更快,但我不知道如何在 python 中做到这一点。

我的最终目标是有一个代码能够找到我在字符串中询问的任何模式(即看起来已通过、警告等)并将模式前面的数字保存到一个变量中,以便稍后添加到字典中。

【问题讨论】:

  • 喜欢 str.find()?

标签: python parsing awk


【解决方案1】:

有几种方法可以解决这个问题。例如,您可以像这样使用正则表达式:

from re import findall

pytest_summary = "1 failed, 316 passed, 204 warnings, 0 skipped, 0 xfailed in 40.82s"
result = findall('([0-9]+) ([a-z]+)', pytest_summary)
print (result)
# --> [('1', 'failed'), ('316', 'passed'), ('204', 'warnings'), ('0', 'skipped'), ('0', 'xfailed')]

所以现在您将零件收集在一个列表中。 要将其转换为字典,同时将数字字符串转换为整数:

result = {key: int(value) for value, key in result}
print (result)
# --> {'failed': 1, 'passed': 316, 'warnings': 204, 'skipped': 0, 'xfailed': 0}

当然,如果你愿意,你可以在一行中完成整个事情:

result = {key: int(value) for value, key in findall('([0-9]+) ([a-z]+)', pytest_summary)}

建议将该代码包装在 try: ... except ValueError: 中,以防输入字符串碰巧包含不是有效整数的内容。

【讨论】:

    【解决方案2】:
    s = '1 failed, 316 passed, 204 warnings, 0 skipped, 0 xfailed in 40.82s'
    parts = [v.strip().split() for v in s.replace(' in ', ',').split(',')]
    
    d = {p[1]: int(p[0]) for p in parts[:-1]}
    duration = ' '.join(parts[-1])
    

    这给了你:

    >>> d
    {'failed': 1, 'passed': 316, 'warnings': 204, 'skipped': 0, 'xfailed': 0}
    
    >>> duration
    '40.82s'
    

    从那里,你可以随心所欲地处理......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-16
      • 2016-10-02
      • 1970-01-01
      • 2020-09-06
      • 2022-01-07
      • 1970-01-01
      • 2014-02-23
      相关资源
      最近更新 更多