python - 如何从网址中提取标题?

标签 python regex string url-parameters urlparse

我有一个标题数据集,例如

http://www.stackoverflow.com/lifestyle/tech/this-is-a-very-nice-headline-my-friend/2013/04/26/acjhrjk-2e1-1krjke4-9el8c-2eheje_story.html?tid=sm_fb

http://www.stackoverflow.com/2015/07/15/sports/baseball/another-very-nice.html?smid=tw-somedia&seid=auto

http://worldnews.stack.com/news/2013/07/22/54216-hello-another-one-here?lite

http://www.stack.com/article_email/hello-one-here-that-is-cool-1545545554-lMyQjAxMTAHFJELMDgxWj

http://www.stack.com/2013/11/13/tech/tricky-one/the-real-one/index.html

http://www.stack.com/2013/11/13/tech/the-good-one.html

http://www.stack.com/news/science-and-technology/54512-hello-world-here-is-a-weird-character#b02g07f20b14

我需要从这些类型的链接中提取正确的标题,即:

  • 这是我 friend 的一个非常好的标题
  • 另一个非常好
  • 这里你好,另一个人
  • 你好,这里很酷
  • 真实的
  • 好人
  • Hello World 这里是一个奇怪的字符

因此该规则似乎找到了 word1-word2-word3 形式的最长字符串 - 右侧有一个 / 或左边框并且没有考虑

  1. 超过 3 位数字的单词(例如第一个链接中的 acjhrjk-2e1-1krjke4-9el8c-2eheje 或第三个链接中的 54216
  2. 排除 .html 之类的内容。

如何在 Python 中使用正则表达式来做到这一点?不幸的是,我相信正则表达式是这里唯一可行的解​​决方案。诸如 yurlurlparse 之类的包可以捕获 url 的路径,但随后我又回到使用正则表达式来获取标题..

非常感谢!

最佳答案

毕竟,正则表达式可能不是您最好的选择。
但是,根据您提出的规范,您可以执行以下操作:

import re

urls = ['http://www.stackoverflow.com/lifestyle/tech/this-is-a-very-nice-headline-my-friend/2013/04/26/acjhrjk-2e1-1krjke4-9el8c-2eheje_story.html?tid=sm_fb',
'http://www.stackoverflow.com/2015/07/15/sports/baseball/another-very-nice.html?smid=tw-somedia&seid=auto',
'http://worldnews.stack.com/news/2013/07/22/54216-hello-another-one-here?lite',
'http://www.stack.com/article_email/hello-one-here-that-is-cool-1545545554-lMyQjAxMTAHFJELMDgxWj',
'http://www.stack.com/2013/11/13/tech/tricky-one/the-real-one/index.html',
'http://www.stack.com/2013/11/13/tech/the-good-one.html',
'http://www.stack.com/news/science-and-technology/54512-hello-world-here-is-a-weird-character#b02g07f20b14']

regex = re.compile(r'(?<=/)([-\w]+)(?=[.?/#]|$)')
digits = re.compile(r'-?\d{3,}-?')

for url in urls:
    substrings = regex.findall(url)
    longest = max(substrings, key=len)
    headline = re.sub(digits, '', longest)
    print headline

<小时/> 这将打印

 this-is-a-very-nice-headline-my-friend
 another-very-nice
 hello-another-one-here
 hello-one-here-that-is-coollMyQjAxMTAHFJELMDgxWj
 the-real-one
 the-good-one
 hello-world-here-is-a-weird-character

参见a demo on ideone.com .

<小时/>

说明

这里,正则表达式使用lookarounds来查找后面的/和前面的.?/#之一。捕获其间的任何单词字符和破折号。
这不是很具体,但如果您正在寻找最长的子字符串并随后消除三个以上的连续数字,这可能是一个很好的起点。
正如评论中已经说过的,使用语言工具可能会更好。

关于python - 如何从网址中提取标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37974359/

相关文章:

python - 用自定义函数模拟移动窗口

javascript - 用于验证逗号分隔数值出现 10 次的正则表达式

sql - Oracle SQL 正则表达式 RegExp_SubStr End Of Line (chr(10) in search text returns null

Java 字符串最佳实践

python - 值错误 : negative dimensions are not allowed

python - Django 。您无权编辑任何内容

javascript - 什么正则表达式会匹配从 0.5 到 24 的这个值

c++ - 在结构指针中修改 C 字符串

对字符串指针数组的打印过程感到困惑

python - 使字符串成为有效的文件名,以后可以将其视为原始字符串