python-如何在python中使用拆分功能 [英] How to use split function for file in python?

查看:95
本文介绍了python-如何在python中使用拆分功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大量信息的文件.例如,所有行都遵循以下相同模式:

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

     <school>Nebraska</school>

我正在尝试使用split函数仅检索"Nebraska".到目前为止,这就是我要的内容,但是我不确定该怎么做才能使它切掉两个部分,而不仅仅是第一个部分.

I am trying to use the split function to only retrieve 'Nebraska'. This is what I have so far, but I'm not sure what to put to make it cut off both parts instead of just the first.

   with open('Pro.txt') as fo:
       for rec in fo:
          print(rec.split('>')[1])

有了这个我得到:

    Nebraska</school

推荐答案

您已经截断了字符串的一部分.保持相同的方式:

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'

也就是说,您应该使用BeautifulSoup之类的HTML解析器来解析HTML.

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

这篇关于python-如何在python中使用拆分功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆