python取括號裡內容 提取括號中字串的內容

2021-10-17 02:41:02 字數 2470 閱讀 5840

string = "will ferrell (nick halsey), rebecca hall (samantha), michael pena (frank garcia)"

import re

pat = re.compile(r'([^(]+)\s*\(([^)]+)\)\s*(?:,\s*|$)')

lst = [(t[0].strip(), t[1].strip()) for t in pat.findall(string)]

編譯的模式有點棘手。這是一條生硬的線,讓反斜槓不那麼瘋狂。意思是:啟動乙個匹配組;匹配任何不是「(」字元的內容,只要它至少是一次,就可以匹配任意次數;關閉匹配組;匹配乙個文字「(」字元;啟動另乙個匹配組;匹配任何不是「)」字元的內容,只要它至少是一次,就可以匹配任意次數;關閉匹配組;匹配乙個文字「)」字元;然後匹配任何空格(包括無空格);然後是非常棘手的事情。真正棘手的部分是不構成匹配組的分組。它不是以「(」開頭,而是以「(?」結尾?:「然後再以「)」結尾。我使用了這個分組,這樣我就可以在其中放置乙個豎線來允許兩種不同的模式:要麼是逗號匹配,後跟任意數量的空格,要麼是到達了行的末尾('$'字元)。

然後我使用pat.findall()查詢模式匹配的string中的所有位置;它自動返回元組。我把它放在乙個列表理解中,並對每個專案呼叫.strip(),以清除空白。

當然,我們可以使正規表示式更加複雜,並讓它返回已經去掉空白的名稱。不過,正規表示式會變得非常毛茸茸的,所以我們將使用python正規表示式中最酷的特性之一:「verbose」模式,在這種模式下,您可以將乙個模式擴充套件到許多行,並根據需要放置注釋。我們使用的是原始的三引號字串,因此反斜槓很方便,多行也很方便。給你:import re

s_pat = r'''

\s* # any amount of white space

([^( \t] # start match group; match one char that is not a '(' or space or tab

[^(]* # match any number of non '(' characters

[^( \t]) # match one char that is not a '(' or space or tab; close match group

\s* # any amount of white space

\( # match an actual required '(' char (not in any match group)

\s* # any amount of white space

([^) \t] # start match group; match one char that is not a ')' or space or tab

[^)]* # match any number of non ')' characters

[^) \t]) # match one char that is not a ')' or space or tab; close match group

\s* # any amount of white space

\) # match an actual required ')' char (not in any match group)

\s* # any amount of white space

(?:,|$) # non-match group: either a comma or the end of a line

pat = re.compile(s_pat, re.verbose)

lst = pat.findall(string)

夥計,那真的不值得你這麼做。

此外,上面的內容保留了名稱中的空白。您可以很容易地規範化空白,以確保它是100%一致的,通過拆分空白和重新加入空格。string = ' will ferrell ( nick\thalsey ) , rebecca hall (samantha), michael\fpena (frank garcia)'

import re

pat = re.compile(r'([^(]+)\s*\(([^)]+)\)\s*(?:,\s*|$)')

def nws(s):

"""normalize white space. replaces all runs of white space by a single space."""

return " ".join(w for w in s.split())

lst = [tuple(nws(item) for item in t) for t in pat.findall(string)]

print lst # prints: [('will ferrell', 'nick halsey'), ('rebecca hall', 'samantha'), ('michael pena', 'frank garcia')]

現在string有愚蠢的空白:多個空格、乙個製表符,甚至還有乙個表單提要(「\f」)。上面的**將其清除,以便名稱由乙個空格分隔。

excel提取括號內的內容

使用mid函式作為主要函式,使用find函式作為定位函式 mid函式可以擷取文字的內容,其函式構造如下 其顯示結果為所擷取的字元段。例如要提取a1格中前十個字元的內容放入b1格 1.選擇b1格,雙擊或f2進入函式編輯欄 2.輸入函式 mid a1,1,10 3.回車執行函式 4.b1格中顯示 abc...

python提取內容 使用Python提取小說內容

具體實現功能如下 輸入 目錄頁的url之後,指令碼會自動分析目錄頁,提取 的章節名和章節鏈結位址。然後再從章節鏈結位址逐個提取章節內容。現階段只是將 從第一章開始,每次提取一章內容,回車之後提取下一章內容。其他 的結果可能有不同,需要做一定修改。在逐浪測試過正常。coding utf8 usr bi...

網頁內容爬取 如何提取正文內容

建立乙個新 一開始沒有內容,通常需要抓取其他人的網頁內容,一般的操作步驟如下 為每個網頁寫特徵分析這個還是太耗費開發的時間,我的思路是這樣的。python的beautifulsoup包大家都知道吧,import beautifulsoup soup beautifulsoup.beautifulso...