用Python检查单词在网页中出现两次

3 投票
2 回答
3378 浏览
提问于 2025-04-17 12:23

我正在登录一个网站,然后在这个网站上进行搜索。从搜索结果中,我查看网页的内容,看看是否找到了匹配的结果。这个过程一切正常,但有个问题就是网站会显示“xyz的搜索结果”,这句话也被我的搜索结果包含在内,所以我总是得到一个正面的结果,尽管实际上可能并没有找到我想要的内容。我的当前代码是:

... Previous code to log in etc...

words = ['xyz']

br.open ('http://www.example.com/browse.php?psec=2&search=%s' % words)
html = br.response().read()

for word in words:
   if word in html:
      print "%s found." % word
   else:
      print "%s not found." % word

为了处理这个问题,我想检查这个词出现的次数。如果出现两次或更多次,那就算是找到了。如果只出现一次,那显然就是“xyz的搜索结果”这句话被算进来了,所以其实是没有找到的。我该如何修改我的代码,以便检查这个词出现了两次,而不仅仅是一次呢?

谢谢

2 个回答

0

简单来说,你想要知道一个特定单词在一段文字中出现了多少次。可以使用字符串的.count()方法。具体可以参考这个链接

3

你可以试试这个,

for word in words:
    if html.count(word)>1:
        #your logic goes here

举个例子

>>> words =['the.cat.and.hat']
>>> html = 'the.cat.and.hat'
>>> for w in words:
...       if html.count(w)>1:
...           print 'more than one match'
...       elif html.count(w) == 1:
...           print 'only one match found'
...       else:
...           print 'no match found'
...
only one match found
>>>

撰写回答