美文网首页
jion()和split() 连接/分割函数的使用

jion()和split() 连接/分割函数的使用

作者: 小飞船1号 | 来源:发表于2020-05-11 14:52 被阅读0次

    join()方法

    str1=str2.join(sequence):用于将序列中的元素(sequence)以指定的字符(str2)连接生成一个新的字符串(str1)。

    str = "-"
    seq = ("a", "b", "c") # 字符串序列
    print(str.join( seq ))
    #输出:a-b-c
    
    content_html = sel.xpath('//*[@itemprop="articleBody"]').extract_first()
    lines = sel.xpath('//*[@itemprop="articleBody"]//text()').extract()
    content = "\n".join(lines)
    #把页面文本通过\n链接起来
    

    split()方法

    通过指定分隔符对字符串进行切片,返回分割后的字符串列表。如果参数 num 有指定值,则分隔 num+1 个子字符串
    语法

    str.split(str, num).

    • str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
    • num -- 分割次数。默认为 -1, 即分隔所有。
    str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
    print(str.split())      # 以空格为分隔符,包含 \n
    print(str.split( ))      # 以空格为分隔符,包含 \n
    print(str.split(' ', 1 )) # 以空格为分隔符,分隔成两个
    # ['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
    # ['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
    # ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
    # 前两个等同于
    

    join()和split()函数结合实例:提取豆瓣电影的介绍一行文字

    def toHtml():
        import requests
        url = 'https://movie.douban.com/top250'
        headers={
            "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
        }
        response = requests.get(url,headers=headers)
        html = response.text
        return html
    
    def process(ctx):
        from lxml import html
        data = html.fromstring(ctx)
        introduce=""
        movie_list = data.xpath("//div[@class='article']//ol[@class='grid_view']/li")
        for i_item in movie_list:
            intr = i_item.xpath(".//div[@class='info']//div[@class='bd']/p[1]/text()")
            # 因为换行符<br>取text()时有两个值,是列表
            for i in intr:
                # 由于有空行和空格,因此先切割成n块,在连接成字符串
                t="".join(i.split())
                introduce=t
            print(introduce)
    print(process(toHtml()))
    

    相关文章

      网友评论

          本文标题:jion()和split() 连接/分割函数的使用

          本文链接:https://www.haomeiwen.com/subject/uaeunhtx.html