【问题标题】:Find number of unique words in Paragraph tags using beautifulsoup使用beautifulsoup查找段落标签中唯一单词的数量
【发布时间】:2023-03-22 14:07:01
【问题描述】:

我对 python 很陌生。我正在尝试实现一个函数,该函数输出段落标签内唯一单词的数量,但在以几种方式编辑这些文本之后。 第一:检索包含在段落标签中的所有文本并将它们转换为小写 第二:去掉我使用的标点符号str.translate(str.maketrans('','',string.punctuation)) 第三:基于空格分隔标记成单词。 第四:输出唯一词的个数。

这是我的代码:

import urllib
def getLength(url):
    r=urllib.request.urlopen(url).read()
    soup = BeautifulSoup(r, 'html.parser')
    links = soup.find_all('p')
    k=[]
    for p in links:
        if not p.find('a'):
            pText = p.get_text()
            k=k.append(pText)
        k=k.lower()
        translator=str.translate(str.maketrans('','',string.punctuation))
        k=k.translate(translator)
    #missing code
getLength("https://en.wikipedia.org/wiki/Google")

我尝试打印值,发现我的逻辑不正确。我不知道如何纠正这一点并继续进行。请帮忙。

编辑:

import urllib
def getLength(url):
    r=urllib.request.urlopen(url).read()
    soup = BeautifulSoup(r, 'html.parser')
    links = soup.find_all('p')
    for p in links:
        pText = p.get_text()
        pText=pText.lower()
        transpText=pText.translate(pText.maketrans('','',string.punctuation))
        print(transpText)
        newdata=transpText.split()
        length=len(newdata)
        return length
getLength("https://en.wikipedia.org/wiki/Google")

我知道了,但我不明白标记化部分。出于某种原因,我得到 0 作为长度。我做错了什么或者应该怎么做。

【问题讨论】:

  • 嗨@JBlack,欢迎来到SO。你提到了logic error。提出一个好问题,您需要 1) 输入 2) 函数的输出 3) 函数应该做什么。有了它,帮助您的人可以更轻松地进行故障排除。
  • 你不能在列表上调用.lower().translate()k是一个列表);改为在pText 上调用它。

标签: python function beautifulsoup


【解决方案1】:
import numpy as np
import urllib
def getLength(url):
    r=urllib.request.urlopen(url).read()
    soup = BeautifulSoup(r, 'html.parser')
    links = soup.find_all('p')
    k=[]
for p in links:
    pText = p.get_text()
    pText=pText.lower()
    transpText=pText.translate(pText.maketrans('','',string.punctuation))
    newdata=transpText.split()
    k += newdata
n=np.unique(k)
return len(n)
getLength("https://en.wikipedia.org/wiki/Google")

在多次尝试之后......这段代码是我登陆的,它似乎适用于各种测试用例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 2022-08-17
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    相关资源
    最近更新 更多