javascript - 关于python,正则表达式作为if判断条件的问题

WBOY
Release: 2016-06-06 20:09:28
Original
1261 people have browsed it

有2000行链接需要进行爬虫处理,可分为以下三种类型,字体加粗。

https://www.coursera.org/course/inforisk
https://www.coursera.org/specializations/cloudcomputing
https://www.coursera.org/learn/python-data

需要在python中写一个正则表达式在作为if条件语句的判断条件,关键词为“/course/” "/specializations/"以及 “/learn/”三个条件,结构如下

if 一行链接 匹配/course/:

<code>'''</code>
Copy after login
Copy after login
Copy after login
Copy after login

elif 一行链接匹配/specializations/:

<code>'''</code>
Copy after login
Copy after login
Copy after login
Copy after login

else 一行链接匹配 /learn/:

<code>'''
</code>
Copy after login
Copy after login

初学python,看了一段正则的教学也没有太理解,求大神写一段可以作为判断条件的匹配,再能推荐些正则的学习资料就更好了!thx!

回复内容:

有2000行链接需要进行爬虫处理,可分为以下三种类型,字体加粗。

https://www.coursera.org/course/inforisk
https://www.coursera.org/specializations/cloudcomputing
https://www.coursera.org/learn/python-data

需要在python中写一个正则表达式在作为if条件语句的判断条件,关键词为“/course/” "/specializations/"以及 “/learn/”三个条件,结构如下

if 一行链接 匹配/course/:

<code>'''</code>
Copy after login
Copy after login
Copy after login
Copy after login

elif 一行链接匹配/specializations/:

<code>'''</code>
Copy after login
Copy after login
Copy after login
Copy after login

else 一行链接匹配 /learn/:

<code>'''
</code>
Copy after login
Copy after login

初学python,看了一段正则的教学也没有太理解,求大神写一段可以作为判断条件的匹配,再能推荐些正则的学习资料就更好了!thx!

仅仅检查是否含有用in就可以了吧?

<code>def check_url(word, url):
    return word in url

for u in urls:
    if check_url('/course/', u):
        do something
    elif check_url('/specializations/', u):
        do something
    elif check_url('/learn/', u):
        do something
</code>
Copy after login

<code>import re
raw = '''
https://www.coursera.org/course/inforisk
https://www.coursera.org/specializations/cloudcomputing
https://www.coursera.org/learn/python-data'''

check_func = lambda url, key: re.search('^https://www.coursera.org/%s/.+' % key, url)
for url in raw.split('\n'):
    if check_func(url, 'course'):
        print 'I m course'
    elif check_func(url, 'specializations'):
        print 'I m specializations'
    elif check_func(url, 'learn'):
        print 'I m learn'
</code>
Copy after login

这里用到了正则.+,其中.是指任意字符,+代表一个以上的字符,.+就是匹配一个以上的任意字符。
Python中re模块是正则相关的模块,这里用到了re.search,如果匹配字符串成功,会返回一个对象,否则返回None
re模块还有其他函数,例如re.findall,re.match,re.replace

直接用in是不可以的,例如如果url是https://www.coursera.org/course/specializations,就会导致specializations和course都能匹配到。
希望可以帮到你。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!