我從網站上颳了幾篇文章。現在我正試圖提取新聞的位置。這個位置用大寫字母表示,只用國家的首都(例如「BRUSSELS-」)或者在某些情況下與國家一起(例如「BRUSELLS,Belgium-」)使用正則表達式匹配位置| Python
這是一篇文章樣本:
|[<p>Advertisement , By MILAN SCHREUER and ALISSA J. RUBIN OCT. 5, 2016
, BRUSSELS — A man wounded two police officers with a knife in Brussels around...]
[<p>Advertisement , By DAVID JOLLY FEB. 8, 2016
, KABUL, Afghanistan — A Taliban suicide bomber killed at least three people on Monday and wounded]
正則表達式我用的是這個:
text_open = open("Training_News_6.csv")
text_read = text_open.read()
pattern = ("[A-Z]{1,}\w+\s\—")
result = re.findall(pattern,text_read)
print(result)
爲什麼我使用的計分標誌的原因( - ),因爲是鏈接到該位置的重複的樣式。
然而,這正則表達式管理提取「布魯塞爾 - 」但是,當談到「阿富汗喀布爾 - 」它只能提取的最後部分,即「阿富汗 - 」。 在第二種情況下,我想提取整個位置:首都和國家。任何想法?
嘗試'r'([A-Z] +)(?:\ W + \ w +)?\ s * - ''。見https://regex101.com/r/ATgIeZ/1 –
當我運行它時,它只匹配大寫字母,當首都後面跟着一個逗號和國家我想要extrac –
只需移動' )'稍遠一點:https://regex101.com/r/ATgIeZ/2 –