我有一个标题数据集,例如
<a href="#first">........</a>
<a href="#second">........</a>
我需要从这些链接中提取正确的标题,即:
所以规则似乎找到了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
形式的最长字符串 - 在右边框或左边框有word1-word2-word3
而没有考虑
/
或第三个链接中的acjhrjk-2e1-1krjke4-9el8c-2eheje
54216
等内容。如何在Python中使用正则表达式执行此操作?不幸的是,我相信正则表达式是唯一可行的解决方案。诸如.html
或yurl
之类的包可以捕获网址的路径,但之后我又回到使用正则表达式来获取标题..
非常感谢!
答案 0 :(得分:1)
毕竟,正则表达式可能不是你最好的选择 但是,根据您提出的规范,您可以执行以下操作:
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
此处,正则表达式使用 lookarounds 来查找后面的/
和.?/#
之一。捕获中间的任何单词字符和短划线
这不是非常具体,但如果你要寻找最长的子串并且之后消除超过三个连续的数字,这可能是一个很好的起点。
正如评论中已经说过的那样,使用语言工具可能会更好。