【问题标题】:Python: counting specific words from HTMLPython:计算 HTML 中的特定单词
【发布时间】:2020-10-04 21:18:54
【问题描述】:

所以,我是一名 Python 新手,学习网络抓取非常困难。我打算计算这个 HTML 页面中的单词数,并显示哪些单词只出现一次,以及“女士”这个词出现了多少次。到目前为止,我已经设法想出了这个:

import requests
from bs4 import BeautifulSoup
import operator
from collections import Counter

def my_start(url):
   my_wordlist = []
   my_source_code = requests.get(url).text
   my_soup = BeautifulSoup(my_source_code, 'html.parser')
   for each_text in my_soup.findAll('p', {'class':'about-text'}):
      content = each_text.text
      words = content.lower().split()
      for each_word in words:
         my_wordlist.append(each_word)
      clean_wordlist(my_wordlist)

def clean_wordlist(wordlist):
   clean_list =[]
   for word in wordlist: 
      symbols = '!@#$%^&*()_-+={[}]|\;:"<>?/., '
      for i in range (0, len(symbols)):
         word = word.replace(symbols[i], '')
      if len(word) > 0:
         clean_list.append(word)
   create_dictionary(clean_list)

def create_dictionary(clean_list):
   word_count = {}
   for word in clean_list:
      if word in word_count:
         word_count[word] += 1
      else:
         word_count[word] = 1
   c = Counter(word_count)
   print(c)
   if word_count[word] == 1:
    print(word)
   top = soup.find_all("ladies")
   print(top)

if __name__ == '__main__':
  my_start("http://brasil.pyladies.com/about/")

我注意到有些词只出现一次而没有在此处显示,还有一个词出现两次并显示出来。我也不知道如何计算“女士”这个词出现的次数。任何有关此事的意见将不胜感激!

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    top = soup.find_all("ladies")

    这里find_all 的用法是错误的。它用于搜索 HTML 标签,而不是单词。

    如果要打印“女士”一词出现的次数,请尝试

    print(word_count.get('ladies','0'))
    

    【讨论】:

      【解决方案2】:

      我建议你使用正则表达式 (regex) 来解决这个问题

      import re
      
      my_source_code = requests.get(url).text
      pattern = "ladies"
      
      ladies_count = len(re.findall(pattern, my_source_code))
      

      这是从文本中计算单词的最快方法

      【讨论】:

      • 非常感谢,之前不知道这个库,真的好用!
      • 你可以from bs4 import BeautifulSoup as bsBeautifulSoup从html内容中提取所有文本然后计数。 all_text = bs(content, "html.parser").text 之后 len(re.find_all(pattern, all_text)) 返回您需要的结果
      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多