繁体   English   中英

如何通过python修复抓取的url数据的正则表达式形式?

[英]How to fix a regular expression form for scraped url data via python?

我正在尝试使用正则表达式清理我的 url 数据。 我已经把它绕过了,但我还有最后一个问题,我不知道如何解决。

这是我从一些新闻中心抓取的数据,它由主题部分和源部分组成

我需要从 url 中抓取源模式并省略主题部分,以便将其放在 numpy 数组中进行进一步分析。

我抓取的网址如下所示:

/video/36225009-report-cnbc-russian-sanctions-ukraine/

/health/36139780-cancer-rates-factors-of-stomach/

/business/36187789-in-EU-IMF-reports-about-world-economic-environment/

/video/35930625-30stm-in-last-tour-tv-album-o-llfl-/?smi2=1

/head/36214416-GB-brexit-may-stops-process-by/

/cis/36189830-kiev-arrested-property-in-crymea/

/incidents/36173928-traffic-collapse-by-trucks-incident/

..............................................................

我已尝试使用以下代码来解决此问题,但它不起作用并返回整个字符串,而不仅仅是主题部分。

import numpy as np
import pandas as pd
import re

regex = r"^/(\b(\w*)\b)"

pattern_two = regex
prog_two = re.compile( pattern_two )

with open('urls.txt', 'r') as f:

    for line in f:
        line = line.strip()
    
    if prog_two.match( line ):
          print( line )

我还检查了正则表达式(在 regex101.com 上),如regex = r"^/(\\b(\\w*)\\b)"regex = r"^/[az]{0,9}./" ,但它也不能正常工作。 我在正则表达式方面没有很强的技能,也许我做错了什么?

我期望的最终结果如下:

video
health
business
video
head
cis
incidents  
...........

非常感谢您的帮助!

更改为以下方法:

regex = r"^/([^/]+)"
pat = re.compile(regex)

with open('urls.txt', 'r') as f:
    for line in f:
        line = line.strip()
        m = pat.search(line)
        if m:
            print(m.group(1))

或者不使用正则表达式,使用内置字符串函数:

...
for line in f:
    line = line.strip()
    if line.startswith('/'):
        print(line.split('/', 1)[0])

您也许可以在这里使用split()

with open('urls.txt', 'r') as f:
    for line in f:
        line = line.strip()   # this might be optional
        if line.startswith('/'):
            print(line.split("/")[1])

一般来说,如果避免调用正则表达式引擎是可能的,为了只使用基本字符串函数,我们应该选择后一个选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM