Heim  >  Fragen und Antworten  >  Hauptteil

So extrahieren Sie den Domänennamen mithilfe eines regulären Python-Ausdrucks

<script type="application/ld+json">{
    "@context": "http://schema.org",
    "@type": "SaleEvent",
    "name": "10% Off First Orders",
    "url": "https://www.myvouchercodes.co.uk/coggles",
    "image": "https://mvp.tribesgds.com/dyn/oh/Ow/ohOwXIWglMg/_/mQR5xLX5go8/m0Ys/coggles-logo.png",
    "startDate": "2017-02-17",
    "endDate": "2017-12-31",
    "location": {
        "@type": "Place",
        "name": "Coggles",
        "url": "coggles.co.uk",
        "address": "Coggles"
    },
    "description": "Get the top branded fashion items from Coggles at discounted prices. Apply this code and enjoy savings on your purchase.",
    "eventStatus": "EventScheduled"
}</script>

Wie verwende ich einen regulären Python-Ausdruck, um den Domainnamen coggles.co.uk aus diesem Skript zu extrahieren? Ich hoffe, Experten aus allen Lebensbereichen können mir ihre Fähigkeiten zeigen ...

淡淡烟草味淡淡烟草味2648 Tage vor936

Antworte allen(2)Ich werde antworten

  • ringa_lee

    ringa_lee2017-06-22 11:53:53

    正则实现的话只要保证你的标定/特征是唯一的就好。但是"url"这个标志又不是唯一的。这个时候@prolifes的方法是很好的。

    如果一定要正则实现呢,要用到零宽断言(zero-width assertions),当然这个词的翻译比较直,带来很多误解。它其实意思是指定位置的匹配,位置的宽度就是0嘛。

    这里我们可以看到我们所需的这个"url""location"里面,可以以此为位置信息。

    代码如下:

    re.search('(?<=location).+?"url": "([^"]+)"', string, re.DOTALL).group(1)

    稍微解释一下,
    (?<=location)这个地方就是指前面得有location。后面有的话这样写:(?=location)
    re.DOTALL这个是必须的,因为这些字符串已经跨行了。他的作用是将.的字符串匹配范围扩大,包含换行符。
    "([^"]+)"这个地方是我的习惯,[^"]意指所有非"的字符,这就匹配了双引号中所有的字符串。

    Antwort
    0
  • 世界只因有你

    世界只因有你2017-06-22 11:53:53

    这是一段挺标准的json,粗暴一点,直接转换成json

    import json
    
    str = '''
    <script type="application/ld+json">{
        "@context": "http://schema.org",
        "@type": "SaleEvent",
        "name": "10% Off First Orders",
        "url": "https://www.myvouchercodes.co.uk/coggles",
        "image": "https://mvp.tribesgds.com/dyn/oh/Ow/ohOwXIWglMg/_/mQR5xLX5go8/m0Ys/coggles-logo.png",
        "startDate": "2017-02-17",
        "endDate": "2017-12-31",
        "location": {
            "@type": "Place",
            "name": "Coggles",
            "url": "coggles.co.uk",
            "address": "Coggles"
        },
        "description": "Get the top branded fashion items from Coggles at discounted prices. Apply this code and enjoy savings on your purchase.",
        "eventStatus": "EventScheduled"
    }</script>
    '''
    
    d = json.loads(re.search('({[\s\S]*})', str).group(1))
    print d['location']['url']

    Antwort
    0
  • StornierenAntwort