簡體   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