就像我有一个字符串一样 str1 = "IWantToMasterPython"
如果我想"Py"从上面的字符串中提取.我写:
extractedString = foo("Master","thon")
Run Code Online (Sandbox Code Playgroud)
我想做所有这些,因为我试图从HTML页面中提取歌词.歌词写得像<div class = "lyricbox"> ....lyrics goes here....</div>.
有关如何实施的任何建议.
ton*_*nfa 31
解决方案是使用正则表达式:
import re
r = re.compile('Master(.*?)thon')
m = r.search(str1)
if m:
lyrics = m.group(1)
Run Code Online (Sandbox Code Playgroud)
Thi*_*Lam 10
BeautifulSoup是做你想做的最简单的方法.它可以安装如下:
sudo easy_install beautifulsoup
Run Code Online (Sandbox Code Playgroud)
做你想做的样本代码是:
from BeautifulSoup import BeautifulSoup
doc = ['<div class="lyricbox">Hey You</div>']
soup = BeautifulSoup(''.join(doc))
print soup.find('div', {'class': 'lyricbox'}).string
Run Code Online (Sandbox Code Playgroud)
您可以使用Python的urllib直接从url中获取内容.如果你想做更多的解析,Beautiful Soup doc也很有帮助.
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]
Run Code Online (Sandbox Code Playgroud)
如果领导者不在字符串s中,或者预告片在此之后不存在(你没有在这样的异常条件中指定你想要的行为),那么就会引发ValueError;提出异常是非常自然和Pythonic要做的事情,让调用者使用try/except来处理它,如果它知道在这种情况下该怎么做).
基于RE的方法也是可行的,但我认为这种纯字符串方法更简单.
| 归档时间: |
|
| 查看次数: |
25983 次 |
| 最近记录: |