python - python 中的字数统计

标签 python url beautifulsoup html-parsing word-count

我想计算从网站上获取的文本的字数。 我正在尝试下面的代码:

import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen

def get_text(url):
  page = urlopen(url)
  soup = BeautifulSoup(page, "lxml")
  text = ' '.join(map(lambda p: p.text, soup.find_all('p')))
  return soup.title.text, text

number_of_words = 0

url = input('Enter URL - ')
text = get_text(url)

我想计算此文本变量的字数

服用https://www.ibm.com/in-en/cloud/learn/what-is-artificial-intelligence作为 URL,除了获取文本变量的字数之外,一切都运行良好。

附注- 作为参数输入的word_count计数变量,生成的摘要的字数不同。

我还设法使用以下代码获取从 URL 检索的原始文本的文本字符长度

print('Text character length - ', len(str(text)))

最佳答案

len(str(text)) 将计算字母而不是单词,要计算总单词数,您必须拆分文本 len(str(text).split()):

import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen


def get_text(url):
    page = urlopen(url)
    soup = BeautifulSoup(page, "lxml")
    text = ' '.join(map(lambda p: p.text, soup.find_all('p')))
    return soup.title.text, text


url = input('Enter URL - ')

text = get_text(url)
number_of_words = len(str(text).split())
print(number_of_words)

输出:

1080

关于python - python 中的字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74492107/

相关文章:

Python - Base64 数据是有效图像吗?

python - qwidget.setGeometry() 在 Linux 上的位置不正确

Javascript for循环查找字符串中的URL并更改为链接?

python - findAll-beautifulsoup-python 无法正常工作

python - 使用 NumPy 进行位破解

python - Django - 多个数据库 - 如何定义路由器?

python - Django 绝对 url

zend-framework - Zend 框架 HTTPS URL

python - Web 抓取带有 <pre> 预格式化文本且没有标签的 .htm 页面

python - BeautifulSoup 找不到属性