使用beautifulsoup查找段落标记中的唯一单词数

2024-05-02 13:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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。我做错了什么,或者应该怎么做


Tags: 函数urlstringlinksfindurllibtranslatesoup
1条回答
网友
1楼 · 发布于 2024-05-02 13:38:32
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")

在尝试了多次之后…这段代码就是我遇到的,它似乎可以正确地用于各种测试用例

相关问题 更多 >