如何从python中提取两个其他字符串之间的字符串?

2024-06-14 05:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

就像我有一个类似str1 = "IWantToMasterPython"的字符串

如果我想从上面的字符串中提取"Py"。我写道:

extractedString = foo("Master","thon")

我想做所有这些,因为我正试图从一个html页面提取歌词。歌词写得像<div class = "lyricbox"> ....lyrics goes here....</div>

关于如何实施的任何建议。


Tags: 字符串pydivmasterfoohtml歌词页面
3条回答
def foo(s, leader, trailer):
  end_of_leader = s.index(leader) + len(leader)
  start_of_trailer = s.index(trailer, end_of_leader)
  return s[end_of_leader:start_of_trailer]

如果在字符串s中不存在前导符,或者其后不存在尾符,则会引发ValueError(在这种异常情况下,您没有指定要执行的行为;引发异常是一种非常自然和恶毒的行为,让调用方使用try/来处理,除非它知道在这种情况下要执行什么操作)。

基于RE的方法也是可能的,但我认为这种纯字符串方法更简单。

解决方案是使用regexp:

import re
r = re.compile('Master(.*?)thon')
m = r.search(str1)
if m:
    lyrics = m.group(1)

美貌是做你想做的事最简单的方法。它可以安装如下:

sudo easy_install beautifulsoup

执行所需操作的示例代码是:

from BeautifulSoup import BeautifulSoup

doc = ['<div class="lyricbox">Hey You</div>']
soup = BeautifulSoup(''.join(doc))
print soup.find('div', {'class': 'lyricbox'}).string

您可以使用Python的urllib直接从url获取内容。如果您想做更多的解析,Beautiful Soup doc也很有用。

相关问题 更多 >