search
HomeBackend DevelopmentPython Tutorialpython正则表达式抓取成语网站

1、首先找到一个在线成语网站

2、查看网页结构,定义正则式

看一下要抓的成语的标签有什么特点,查看源码,可以发现要抓的成语都在标签中,如:安如磐石,成语事实上就是一个瞄文本,不同成语指向的链接不同,其实也就"/cy0/93.html"中的数字不同,所以正则式里匹配两次数字就行了,定义正则式 reg =   "(.*?)"。
3、上代码吧

复制代码 代码如下:

#anthor jiqunpeng
#time 20121124
import urllib
import re

def getHtml(url): #从URL中读取html内容
    page = urllib.urlopen(url)
    html = page.read()
    page.close()
    return html

def getDictionary(html): #匹配成语
    reg = "(.*?)"  
    dicList = re.compile(reg).findall(html)
    return dicList

def getItemSite():#手工把每个字母开头的页面数统计下来
    itemSite = {}#申明为空字典
    itemSite["A"] = 3
    itemSite["B"] = 21
    itemSite["C"] = 19
    itemSite["D"] = 18
    itemSite["E"] = 2
    itemSite["F"] = 14
    itemSite["G"] = 13
    itemSite["H"] = 15
    itemSite["J"] = 23
    itemSite["K"] = 6
    itemSite["L"] = 15
    itemSite["M"] = 12
    itemSite["N"] = 5
    itemSite["O"] = 1
    itemSite["P"] = 6
    itemSite["Q"] = 16
    itemSite["R"] = 8
    itemSite["S"] = 26
    itemSite["T"] = 12
    itemSite["W"] = 13
    itemSite["X"] = 16
    itemSite["Y"] = 35
    itemSite["A"] = 21
    return itemSite
   

if __name__== "__main__":
    dicFile = open("dic.txt","w+")#保存成语的文件
    domainsite = "http://chengyu.itlearner.com/list/"
    itemSite = getItemSite()
    for key,values in itemSite.items():
        for index in range(1,values+1):
            site = key +"_"+str(index)+".html"             
            dictionary = getDictionary(getHtml(domainsite+site))
            for dic in dictionary:
                dicFile.write(dic[2]+"@@CY\n")#标记为成语,分词时使用
        print key+'字母成语抓取完毕'       
    dicFile.close()   
    print '全部成语抓取完毕'

把成语保存在了txt文本中,还添加了一个后缀标签。
最后注意,设计正则表达式时可能会出现明明认为是正确的,就是匹配不了,对空白字符要留意,比如说要解析:

复制代码 代码如下:

                kkun

           


你看不出第一行与第二行的空白字符是什么,可以index = html.find('avatar_name'),html[4677:4677+100]看到非空白字符。

Statement
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
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)