首页 > 解决方案 > 如何通过python修复抓取的url数据的正则表达式表单?

问题描述

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

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

我需要从 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 上) likeregex = r"^/(\b(\w*)\b)"和 like regex = r"^/[a-z]{0,9}./",但它也不能正常工作。我在正则表达式方面没有很强的技能,也许我做错了什么?

我期望的最终结果如下:

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

非常感谢您的帮助!

标签: pythonregexpython-3.xdata-cleaning

解决方案


更改为以下方法:

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])

推荐阅读