从特定文本中删除多个单词的任何特定方法?

时间:2013-08-21 03:25:43

标签: python python-3.x html-parsing beautifulsoup

我会给出一些代码的嗤之以鼻。这是:

url = urlopen("http://sports.yahoo.com/nhl/scoreboard?d=2013-01-19")
content = url.read()
soup = BeautifulSoup(content)

def yahooscores():
    for table in soup.find_all('table', class_='player-title'):
        for row in table.find_all('tr'):
            date = None
            for cell in row.find_all('td', class_='yspsctnhdln'):
                for text in cell:
                    date = cell.text
            if date is not None:
                print ('%s' % (date) + ", 2013:")

我试图从网站的日期部分剥离“Scores& Schedules”这个词,但我无法以某种方式使用.split()和.strip()方法。

所以,让我以上述网站为例解释我想做什么。

到目前为止,这是约会的结果:

Scores & Schedule: Jan 19, 2013:

我只想要这个:

Jan 19, 2013:

为了剥掉这3个字,我还需要知道什么吗?

5 个答案:

答案 0 :(得分:1)

cell.text的实际内容是:

'\nScores & Schedule: Jan 19\n'

...因此,首先获得您需要的内容(最后两个单词)更有意义,然后添加', 2013:',因为我认为你'重新尝试做。 split()的一个方便功能是它会自动删除前导空格和尾随空格,因此获得所需内容的最强大方法可能是将最后一行更改为:

                print(' '.join(date.split()[-2:]) + ', 2013:')

这会将date拆分为包含.split()的单词列表,然后使用[-2:]获取列表中的最后两个单词,然后使用{{}将其与空格连接在一起1}},最后在打印结果之前将' '.join(...)添加到结尾。

作为旁注,原始版本中的', 2013:'绝对没有任何内容:您所做的只是用自己替换'%s' % (date)。可能值得熟悉the documentation on percent-formatting,以便了解原因。

答案 1 :(得分:0)

只需用空字符串替换不需要的部分即可。

>>> "Scores & Schedule: Jan 19, 2013:".replace("Scores & Schedule:", "")
' Jan 19, 2013:'

答案 2 :(得分:0)

保持简单:

>>> s = "Scores & Schedule: Jan 19, 2013:"
>>> s.replace("Scores & Schedule:", "")
' Jan 19, 2013:'

答案 3 :(得分:0)

date = "Scores & Schedule: Jan 19, 2013:"

有很多选择:

date = date[19:]

date = date.replace("Scores & Schedule: ", "")

date = date.split(":")[1].strip()+":"

仅举几例。

答案 4 :(得分:0)

怎么样:

print(date[20:].strip('\n') + ', 2013')

这假设总是会有'得分&时间表:'在回复中。