簡體   English   中英

Python - 如何刪除子字符串中直到並包括關鍵字的所有字符

[英]Python - How to delete all characters in a sub string up to and including a keyword

我在一列的數據框中有一個相當大的語料庫(50 萬篇新文章)。 大多數(並非全部)文章的開頭都有各種隨機丟棄的文本,直到短語“(路透社) - ”

我嘗試了以下正則表達式的各種排列,試圖一次性調整整個列,但沒有運氣,因為它要么刪除了大量文章,要么什么都不做。

r = re.compile(r'\A\b.*[Reuters]\b')
reuters3 = reuters2['story_text'].str.replace(r,'', regex=True)

關於如何從正則表達式和熊貓方法的角度最好地解決這個問題的任何想法? 謝謝你

下面提供了一個例子,顯示了在開始時要刪除的文本的一般模式(直到並包括(路透社)-),保持在中間擺脫和在結束時擺脫(接下來的所有內容,包括(編輯者...)。在這些關鍵切斷詞之外的文章中,確切的語言、字符和長度差異很大。

克里斯·西克盧納 瓦萊塔,1 月 1 日(路透社)——周二午夜時分,地中海島嶼馬耳他成為歐元區最小的成員......獲得廣泛認可的成功。 (Michael Winfrey 編輯) ((gavin.jones@reuters.com; +39-06-8522-4232; Reuters Messaging: gavin.jones.reuters.com@reuters.net)) 關鍵詞:ECB EXPANSION/EURO MALTA

如果你需要保留這個詞,你可以使用

reuters2['story_text'].str.replace(r'(?s)^.*?(?=\(Reuters\)\s*-)', '')

如果你沒有需要保留的話,你可以使用

reuters2['story_text'].str.replace(r'(?s)^.*?\(Reuters\)\s*-\s*', '')

或者,像這樣使用Series.str.split

import pandas as pd
df = pd.DataFrame({'story_text':['Some rubbish ... (Reuters) - Text']})
df['story_text'].str.split(r'\(Reuters\)\s*-', n=1).str[-1]
# => 0     Text

細節

  • (?s) - DOTALL 修飾符,使. 匹配任何字符
  • ^ - 字符串的開始
  • .*? - 盡可能少的任何 0 個或更多字符
  • \\(Reuters\\) - 文字(Reuters)文本
  • (?=\\(Reuters\\)\\s*-) - 與緊隨其后的位置匹配的正向前瞻(Reuters) ,0+ 空格和-
  • \\s*-\\s* - -用 0+ 個空格包圍。

請參閱正則表達式演示 #1正則表達式演示 #2

split解決方案使用更簡單的正則表達式\\(Reuters\\)\\s*-並將字符串拆分為 2 部分(因為定義了n=1n是拆分的數量)並且.str[-1]得到最后(這里是第二個)項目。

只需.split()就可以了

parts = starting_string.split("Reuters", 1)  # split at most once
story = parts[-1]  # get the last part

例子

>>> s = "blah blah Reuters bulk of the story"
>>> s.split("Reuters", 1)
['blah blah ', ' bulk of the story']
>>> "missing the newsgroup!".split("Reuters", 1)
['missing the newsgroup!']
>>> ["start", "end"][-1]
'end'
>>> ["bulk without splitword"][-1]
'bulk without splitword'

在拆分目標周圍添加空格或其他字符也可能有所幫助

全部一起:

>>> s = "blah blah Reuters bulk of the story"
>>> s.split(" Reuters ", 1)[-1]
'bulk of the story'

您可能想要針對可能的情況進行一些額外的驗證,即您的拆分字符串不是簡單地在標題中沒有的文章中的某處提及。 也許簡單地說,如果有兩個部分,第二個比第一個長,最多 N 個字符。

暫無
暫無

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

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