【发布时间】:2021-07-02 11:09:09
【问题描述】:
我有一个字符串,其中包含文本和字符串中的 URL 实例数。由于 myString 是一个变量,因此每次在 myString 的不同部分中都可能没有一个或多个 URL 实例,我希望只有在存在任何 URL 时才将 myString 拆分为多条消息。否则它只会是一条消息。
我正在寻找一种方法将 myString 中的文本单词/句子与 URL 分开,但保持对话中的顺序,例如:
message1: Text: "Hello world,"
message2: URL: "https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles"
message3: Text: "in the portal of"
message4: URL: "http://www.geeksforgeeks.org/"
message5: Text: ". Sample text goes here"
... #and so on...
我假设我需要将我的字符串转换为嵌套字典,但不完全确定如何实现这一点。有人可以给我一些提示吗?提前谢谢你。
myString = "Hello world, https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of http://www.geeksforgeeks.org/. Sample text goes here www.google.com but also here https://google.com lorem ipsum google.com/contact-us multiple urls within text."
【问题讨论】:
-
这个
message4: URL: "http://www.geeksforgeeks.org/"不是python中的有效字典 -
为什么你认为字典是最好的数据结构?看起来列表会更合适,因为它保持元素的顺序,并且您的字典键实际上只是字符串“消息”+索引。
-
关于您的问题,我会在 Google 上搜索 URL 的正则表达式,并使用它将字符串拆分为单独的 URL/非 URL 部分。
标签: python string dictionary split