python - 如何通过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
...........
非常感谢您的帮助!
解决方案
更改为以下方法:
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])
推荐阅读
- python - 如何将python`for`循环转换为c++
- c++ - 在字符变量上使用 toupper() 时,所述 char 变量输出多个字符。我将如何防止这种情况?
- c# - 复选框的方法方程问题
- javascript - GatsbyJS 页面从 URL 打开时打开空白(使用博客导航正常工作)
- html - 为什么我的导航栏和页脚没有拉伸到全宽?
- shell - 运行 Hyperledger Fabric 示例“构建您的第一个网络”时“加载 ClientOU 证书失败”
- python - 运行对象检测程序 Abort Trap 时出错:6
- ruby-on-rails - ruby 升级后启动 Rails 服务器时出错
- angular - Angular Reactive Form 如何存储 JSON 数据?
- java - 无法转换为 org.springframework.security.core.userdetails.UserDetails,根本原因是 Java spring-boot 安全性错误