Python 如何从一个字符串中解析出 2 个 URL,然后将其映射回来?

Python how to parse 2 URLs from a string and then map it back?

我在 pandas 数据框中有一列,其中一些值采用这种格式:"From https://....com?gclid=... to https://...com". What I would like is to parse only the first URL so that the gclid and other IDs would vanish and I would like to map back that into the dataframe e.g.: "From https://....com to https://...com"

我知道有一个名为 urllib 的 python 模块,但如果我将其应用于此字符串并在其上调用 path(),它只会解析第一个 URL 然后我输了与第一部分一样重要的另一部分。

有人可以帮助我吗?谢谢!

如果您使用 DataFrame,则使用 replace(),它可以使用正则表达式查找像 "?.... " 这样的文本(以 ? 开头并以 space 结尾 - 或者以 space 开头使用 ? 并且只有字符不同于 space - '\?[^ ]+')

import pandas as pd

df = pd.DataFrame({'text': ["From https://....com?gclid=... to https://...com"]})

df['text'] = df['text'].str.replace('\?[^ ]+', '')

结果

                                     text
0  From https://....com to https://...com

顺便说一句: 你也可以尝试更复杂的正则表达式来确保它是 url 的一部分,它以 http 开头。

df['text'] = df['text'].str.replace('(http[^?]+)\?[^ ]+', '\1')

我使用 (...)?... 之前捕获这个 url 然后我使用 \1 把它放回去(已经没有 ?...