簡體   English   中英

使用正則表達式在字符串 Python 中查找和合並單詞

[英]Use regex to find and merge words in a string Python

我正在嘗試找到一種方法來匹配和合並來自如下字符串的團隊名稱。 我用正則表達式嘗試了幾種不同的方法,但沒有成功。 幾個例子:

'30 Detroit Red Wings 12 47:06 3 8 1 3 7 0.292'

'31 Los Angeles Kings 11 47:45 4 7 0 4 8'

24 Anaheim Ducks 12 47:49 7 5 0 7 14 0.583

我希望 output 看起來像這樣:

[30, 'Detroit Red Wings', 12, 47:06, 3, 8, 1, 3, 7, 0.292]

[24, 'Anaheim Ducks', 12, 47:49, 7, 5, 0, 7, 14, 0.583]

這是我嘗試使用正則表達式但沒有成功的方法:

pattern = re.compile(r'\b\w+\b')
matches = pattern.finditer(i)

這是使用re.findall的選項:

inp = '30 Detroit Red Wings 12 47:06 3 8 1 3 7 0.292'
matches = re.findall(r'\d+:\d+|\d+(?:\.\d+)?|[A-Za-z]+(?: [A-Za-z]+)*', inp)
print(matches)

這打印:

['30', 'Detroit Red Wings', '12', '47:06', '3', '8', '1', '3', '7', '0.292']

使用的正則表達式模式匹配時間字符串、整數/浮點數或一系列純字母單詞:

\d+:\d+                    match a time string (e.g. '47:06')
|                          or
\d+(?:\.\d+)?              match an integer/floating point number
|                          or
[A-Za-z]+(?: [A-Za-z]+)*   match a series of words (e.g. Detroit Red Wings)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM