How to use split function for file in python?

后端 未结 3 1625
独厮守ぢ
独厮守ぢ 2021-01-28 05:53

I have a file with a bunch of information. For example, all of the lines follow the same pattern as this:

     Nebraska


        
相关标签:
3条回答
  • 2021-01-28 06:15
    s = '<school>Nebraska</school>'
    

    in:

    s.split('>')
    

    out:

    ['<school', 'Nebraska</school', '']
    

    in:

    s.split('>')[1].split('<')
    

    out:

    ['Nebraska', '/school']
    

    in:

    s.split('>')[1].split('<')[0]
    

    out:

    'Nebraska'
    
    0 讨论(0)
  • 2021-01-28 06:20

    You've cut off part of the string. Keep going in the same fashion:

    >>> s = '<school>Nebraska</school>'
    >>> s.split('>')[1]
    'Nebraska</school'
    >>> s.split('>')[1].split('<')[0]
    'Nebraska'
    

    That said, you should parse HTML with an HTML parser like BeautifulSoup.

    0 讨论(0)
  • 2021-01-28 06:31

    You could use a regular expression:

    import re
    regexp = re.compile('<school>(.*?)<\/school>')
    
    with open('Pro.txt') as fo:
        for rec in fo:
            match = regexp.match(rec)
            if match: 
                text = match.groups()[0]
                print(text)
    
    0 讨论(0)
提交回复
热议问题