我有以下文字:
text_main = "The following leagues were identified: sport: basketball league: N.B.A. style: c.123>d sport: soccer league: E.P.L. sport: football league: N.F.L. style: c.124>d. The other leagues aren't that important."
我需要提取所有運動名稱(在 之后sport:)和風格(在之后style:)并創建新列作為sports和style。我正在嘗試使用以下代碼來提取主句(有時文本很大):
m = re.split(r'(?<=\.)\s (?=[A-Z]\w )', text_main)
text = list(filter(lambda x: re.search(r'leagues were identified', x, flags=re.IGNORECASE), m))[0]
print(text)
The following leagues were identified: sport: basketball league: N.B.A. style: c.123>d sport: soccer league: E.P.L. sport: football league: N.F.L. style: c.124>d.
然后我提取運動和風格名稱并將它們放入資料框中:
if 'sport:' in text:
sport_list = re.findall(r'sport:\W*(\w )', text)
df = pd.DataFrame({'sports': sport_list})
print(df)
sports
0 basketball
1 soccer
2 football
但是,我在提取樣式時遇到了麻煩,因為所有樣式.在第一個字母 ( c) 之后都有句點,而很少有 sign >。此外,并非所有運動都有風格資訊。
期望的輸出:
sports style
0 basketball c.123>d
1 soccer NA
2 football c.124>d
最聰明的做法是什么?任何建議,將不勝感激。謝謝!
uj5u.com熱心網友回復:
您可以使用
\bsport:\s*(\w )(?:(?:(?!\bsport:).)*?\bstyle:\s*(\S ))?
請參閱正則運算式演示。詳情:
\b- 單詞邊界sport:- 固定字串\s*- 零個或多個空格(\w )- 第 1 組:一個或多個單詞字符(?:- 一個可選的非捕獲組的開始:(?:(?!\bsport:).)*?- 除換行符以外的任何字符,零次或多次出現但盡可能少,不會開始整個單詞sport:字符序列\bstyle:- 一個完整的詞style,然后:\s*- 零個或多個空格(\S )- 第 1 組:一個或多個非空白字符
)?- 可選非捕獲組的結束。
查看 Python 演示:
import pandas as pd
text_main = "The following leagues were identified: sport: basketball league: N.B.A. style: c.123>d sport: soccer league: E.P.L. sport: football league: N.F.L. style: c.124>d. The other leagues aren't that important."
matches = re.findall(r'\bsport:\s*(\w )(?:(?:(?!\bsport:).)*?\bstyle:\s*(\S ))?', text_main)
df = pd.DataFrame(matches, columns=['sports', 'style'])
輸出:
>>> df
sports style
0 basketball c.123>d
1 soccer
2 football c.124>d.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477274.html
