7

这就是我在 ipython 中所做的(我使用的是 Python 3.6)

from PyDictionary import PyDictionary
dictionary = PyDictionary()
list = dictionary.synonym("life")

我得到了错误:

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyDictionary/utils.py:5: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 5 of the file /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyDictionary/utils.py. To get rid of this warning, pass the additional argument 'features="html5lib"' to the BeautifulSoup constructor.

  return BeautifulSoup(requests.get(url).text)
life has no Synonyms in the API

我尝试的每个单词都会发生这种情况,我做错了什么吗?是我需要添加参数'features="html5lib"'的问题吗,如果是,BeautifulSoup 构造函数在哪里,我该怎么做?

4

4 回答 4

2

这是萨兰·罗伊回答的更新版本:

import requests
from bs4 import BeautifulSoup

def synonyms(term):
    response = requests.get('https://www.thesaurus.com/browse/{}'.format(term))
    soup = BeautifulSoup(response.text, 'lxml')
    soup.find('section', {'class': 'css-17ofzyv e1ccqdb60'})
    return [span.text for span in soup.findAll('a', {'class': 'css-1kg1yv8 eh475bn0'})] # 'css-1gyuw4i eh475bn0' for less relevant synonyms

word = "Input Your Word Here!"
print(synonyms(word))
于 2020-06-15T18:45:58.607 回答
1

PyDictionary.synonym函数尝试在 thesaurus.com 上查找同义词,但代码已过时。它正在寻找不再存在的 html 结构。下面的代码将做基本相同的事情:

import requests
from bs4 import BeautifulSoup

def synonyms(term):
    response = requests.get('http://www.thesaurus.com/browse/{}'.format(term))
    soup = BeautifulSoup(response.text, 'html')
    section = soup.find('section', {'class': 'synonyms-container'})
    return [span.text for span in section.findAll('span')]

您可能想要添加一些错误处理。

于 2019-03-24T04:17:52.427 回答
1

ofekcohen'answer 的更新版本

def synonyms(term):
    response = requests.get('https://www.thesaurus.com/browse/{}'.format(term))
    soup = BeautifulSoup(response.text, 'html.parser')
    soup.find('section', {'class': 'css-191l5o0-ClassicContentCard e1qo4u830'})
    return [span.text for span in soup.findAll('a', {'class': 'css-1kg1yv8 eh475bn0'})] 
于 2021-11-28T19:45:27.200 回答
0

尝试这个:

import requests
from bs4 import BeautifulSoup

def synonyms(term):
    response = requests.get('https://www.thesaurus.com/browse/{}'.format(term))
    soup = BeautifulSoup(response.text, 'lxml')
    soup.find('section', {'class': 'synonyms-container'})
    return [span.text for span in soup.findAll('a', {'class': 'css-18rr30y'})] # class = .css-7854fb for less relevant

print(synonyms("reticulum"))

它只是 Nathan Vērzemnieks 答案的修改版本。

于 2020-05-06T14:05:44.660 回答