繁体   English   中英

Python findall() 开始数字和结束单词

[英]Python findall() start digit and end word

我有这个字符串

procesor = "2x2.73 GHz Mongoose M5 & 2x2.50 GHz Cortex-A76 & 4x2.0 GHz Cortex-A55"

我需要使用 re.findall() 这个 CPU 核心列表

Out:['2x2.73 GHz', '2x2.50 GHz', '4x2.0 GHz']

请帮我。 我被困在这里:

re.findall('(\d+[A-Za-z])',procesor)
Out[1]: ['2x', '2x', '4x']

re.findall(r'\d+x\d+(?:\.\d+)?\s*GHz', procesor)

请参阅正则表达式证明

解释

--------------------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  x                        'x'
--------------------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    \.                       '.'
--------------------------------------------------------------------------------
    \d+                      digits (0-9) (1 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  GHz                      'GHz'

如果您需要不区分大小写:

re.findall(r'\d+x\d+(?:\.\d+)?\s*GHz', procesor, re.I)

在更易于阅读的格式中[0-9]表示一位数字:

processor = "2x2.73 GHz Mongoose M5 & 2x2.50 GHz Cortex-A76 & 4x2.0 GHz Cortex-A55"
re.findall(r'[0-9]+x[0-9]+.[0-9]* GHz', processor)

返回:

['2x2.73 GHz', '2x2.50 GHz', '4x2.0 GHz']

这个正则表达式模式可以帮助你: ([\\d.]+)\\s?[xX]\\s?([\\d.]+)\\s?GHz或不敏感的情况(?i)([\\d.]+)\\s?x\\s?([\\d.]+)\\s?GHz

请参阅regex101 中的示例!

将其附加到您的 Python 源代码中:

processor  = """2x2.73 GHz Mongoose M5 & 2x2.50 GHz Cortex-A76 & 4x2.0 GHz Cortex-A55"""
CPU_Cores = re.findall("([\d.]+)\s?[xX]\s?([\d.]+)\s?GHz", processor)
print (CPU_Cores)

输出

[('2', '2.73'), ('2', '2.50'), ('4', '2.0')]

说明

([\\d.]+)\\s?[xX]\\s?([\\d.]+)\\s?GHz

  • 第一组([\\d.]+)匹配第一个实数。
  • \\s?[xX]\\s? 匹配x , x , x , X , X , X
  • 第二组([\\d.]+)匹配第二个实数。
  • \\s? 是可选的,匹配whitespace character或不匹配。
  • GHz字面上匹配 GHz 一词。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM