如何删除 pandas 数据框行中文本之间的 url?
How to remove urls between texts in pandas dataframe rows?
我正在尝试解决一个 nlp 问题,这里的数据框文本列中有很多行填充了 urls
,例如 http.somethingsomething
。一些 url 和其他文本有例如,它们之间没有 space- ':http:\something'
、';http:\something'
、',http:\something'
.
所以在 url
文本之前有时 ,
没有任何 space 有时还有其他内容但主要是 ,
,.
,:
, ;
。 url 在开头或结尾。
id
text
target
1
we always try to bring the heavy metal rt http:\something11
1
4
on plus side look at the sky last night it was ablaze ;http:\somethingdifferent
1
6
inec office in abia set ablaze :http:\itsjustaurl
1
3
.http:\something11
we always try to bring the heavy metal rt
1
所以我想知道如何删除这些链接。我正在使用 python
语言来完成任务。
一个简单的方法是删除任何以 http
或 https
:
开头的 URL
df["text"] = df["text"].str.replace(r'\s*https?://\S+(\s+|$)', ' ').str.strip()
上面这行代码中有一些微妙的逻辑,值得解释一下。我们捕获一个 URL,左边是可选的 whitespace,右边是强制性的 whitespace(除非 URL 持续到最后)。然后,我们将其替换为单个 space,并使用 strip()
以防此操作会在 start/end.
处留下悬垂的白色 space
我正在尝试解决一个 nlp 问题,这里的数据框文本列中有很多行填充了 urls
,例如 http.somethingsomething
。一些 url 和其他文本有例如,它们之间没有 space- ':http:\something'
、';http:\something'
、',http:\something'
.
所以在 url
文本之前有时 ,
没有任何 space 有时还有其他内容但主要是 ,
,.
,:
, ;
。 url 在开头或结尾。
id | text | target |
---|---|---|
1 | we always try to bring the heavy metal rt http:\something11 |
1 |
4 | on plus side look at the sky last night it was ablaze ;http:\somethingdifferent |
1 |
6 | inec office in abia set ablaze :http:\itsjustaurl |
1 |
3 | .http:\something11 we always try to bring the heavy metal rt |
1 |
所以我想知道如何删除这些链接。我正在使用 python
语言来完成任务。
一个简单的方法是删除任何以 http
或 https
:
df["text"] = df["text"].str.replace(r'\s*https?://\S+(\s+|$)', ' ').str.strip()
上面这行代码中有一些微妙的逻辑,值得解释一下。我们捕获一个 URL,左边是可选的 whitespace,右边是强制性的 whitespace(除非 URL 持续到最后)。然后,我们将其替换为单个 space,并使用 strip()
以防此操作会在 start/end.