【问题标题】:Extract URL in JSON String with Python using re.match() or split()使用 Python 使用 re.match() 或 split() 提取 JSON 字符串中的 URL
【发布时间】:2020-08-19 07:56:08
【问题描述】:

使用我的 Python 代码,我提取了 JSON 文件的特殊部分(列表中的列表或字典的一部分):

import json
import urllib

f = open('json-test-file-for-insta-url-snippet.json')
data = json.load(f)

print(json.dumps(data["event"]["attachments"][0]["text"]))

我得到了这个结果:

"\u201cUNLIMITED LIVE\u201d world tour moved to 2021!\nDue to the Covid-19 pandemic and the subsequent regulations and concert restrictions, the world tour, originally planned for the autumn of 2020, could not take place. \n\"\u201eI was very much looking forward to our tour in autumn 2020 all over the world, so I\u2019m deeply sorry that these concerts had to be rescheduled due to the Covid-19 pandemic. I\u2019m very happy that we have already found new dates for our tour in autumn 2021, because I cannot wait to return to get back on stage and to play for you guys. Take care of yourselves \u2013 I hope to see you all happy and healthy again very, very soon!\u201d \nAll your tickets remain valid for the new dates! Please find them below: \n\nKAZ Almaty - Sep 11, 2021\nRUS Yekaterinburg - Sep 14, 2021\nRUS Kazan, Sep 16, 2021\nRUS Voronezh - Sep 18, 2021\nRUS Krasnodar - Sep 20, 2021\nRUS Moscow - Sep 22, 2021\nRUS St. Petersburg - Sep 24, 2021\nUKR Kharkiv - Sep 26 2021\nUKR Odessa - Sep 28, 2021\nUKR Kiev - Sep 30, 2021\nITA Bolzano - Oct 13, 2021\nITA Bologna - Oct 15, 2021\nITA Genoa - Oct 16, 2021\nITA Milano - Oct 17, 2021\nITA Conegliano Veneto - Oct 19, 2021\nBG Sofia - Oct 24, 2021\nRO Bucharest - Oct 26, 2021\nRO Cluj - Oct 29, 2021  #davidgarrett #tour2021 #unlimited #live #postponed\n*Score* -2.57x | *Likes* 338 (-830) | *Comments* 13 (-46)\n_Posted on Tuesday, August 18 at 9:59 AM CEST <https://www.instagram.com/p/CEBew-xHwhJ/|(Instagram)>_\n_Received via Viral Alert_"

现在我想最后提取 Insta-URL - 我如何在 Python 中完成?只有正则表达式才有可能还是有更聪明的方法?我在 Stackoverflow 中阅读了很多内容,但对我没有任何帮助。请帮忙!

【问题讨论】:

    标签: python json url


    【解决方案1】:

    您可以使用以下正则表达式从您的文本中提取 Instagram 链接:

    <(.+)\|\(Instagram\)>
    

    See here

    它搜索由&lt;|(Instagram)&gt;包裹的任何文本并将其存储在捕获组中。


    你可以这样使用它

    import re
    
    INSTA_LINK_RE = re.compile(r'<(.+)\|\(Instagram\)>')
    
    match = INSTA_LINK_RE.search(json.dumps(data["event"]["attachments"][0]["text"]))
    
    if match:
        url = match[1]  # gets the first capturing group
    

    如果您只想获取简码,请使用this regex

    <https://www.instagram.com/p/(.+)/\|\(Instagram\)> 
    

    如果您有一个 str 对象要使用您的 str 正则表达式进行分析,则此方法有效。

    如果你的文本是bytes对象,你需要先解码...

    # JSON files are normally encoded with UTF-8
    json.dumps(data["event"]["attachments"][0]["text"]).decode('utf8`)
    

    ...或使用bytes 正则表达式

    # note the `b` prefix for the regex pattern
    INSTA_LINK_RE = re.compile(br'<(.+)\|\(Instagram\)>')
    

    要直接获取包含str 对象的字典,您还可以将编码传递给open 函数:

    f = open('json-test-file-for-insta-url-snippet.json', encoding='utf-8`)
    

    查看一些 python 文档以了解更多信息:

    【讨论】:

    • 谢谢大家,这对我帮助很大!它适用于我的简而言之的实验,当我直接使用 data = stringxyz 给出字符串时 - 但是当我尝试从本地 json 文件中获取简码结果时,出现错误:
    • import re import json f = open('json-test-file-for-insta-url-snippet.json') data = json.load(f) print(json.dumps(data["event"]["attachments"][0]["text"])) print(re.findall("&lt;https://www.instagram.com/p/(.+)/\|\(Instagram\)&gt;", data)) 输出:File "get-text-from-attachements.py", line 47, in &lt;module&gt; print(re.findall("&lt;https://www.instagram.com/p/(.+)/\|\(Instagram\)&gt;", data)) File "/usr/lib/python3.8/re.py", line 239, in findall return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object 我做错了什么?
    • 从文件中读取文本后,您将获得一个bytes 对象而不是str 对象。您必须解码字节以获得正确的字符串。 JSON 文件以 UTF8 编码,因此您必须使用 data.decode('uft8')。另见docs.python.org/3.6/library/…
    • ok thx,我试过 print(re.findall("&lt;https://www.instagram.com/p/(.+)/\|\(Instagram\)&gt;", data.decode('utf8'))) 并得到:File "get-text-from-attachements.py", line 47, in &lt;module&gt; print(re.findall("&lt;https://www.instagram.com/p/(.+)/\|\(Instagram\)&gt;", data.decode('utf8'))) AttributeError: 'dict' object has no attribute 'decode' 字典有特殊的解码任务吗?
    • 编码涉及文本数据。你的 datavariables 实际上是一个字典,因为它包含你解析的 JSON。请查看更新后的答案及其底部的链接
    【解决方案2】:

    由于结果是字符串格式。正则表达式是最聪明的方法(需要时间学习,但它是一个非常强大的工具)。但是,您可以使用名为instaloader 的模块。不确定您使用的是什么,但 instaloader 对 Instagram 确实很有帮助。

    【讨论】:

    • 非常感谢,我会检查一下,但我只需要该 JSON 字符串中的 URL(或简码)。我用正则表达式尝试了它,比如 'print(re.findall("(?Phttps?://[^\s]+)", data))' 但我得到了 'TypeError: expected string or bytes-like对象':-/
    【解决方案3】:
    import json
    
    link = json.dumps(data["event"]["attachments"][0]["text"])
    link_list = ','.split(link)
    for x in link_list:
        x = x[19:]
        if x.stratswith('https:'):
            i = '|'.split(x)
            link = i[0]
    

    首先我将数据拆分为列表,然后浏览列表,直到找到以 https:(链接) 开头的内容。然后在链接末尾再次拆分并从列表中提取它

    【讨论】:

      猜你喜欢
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多