# 导入requests和BeautifulSoup库
import requests
from bs4 import BeautifulSoup
# 定义一个函数,根据单词查询有道词典,并返回读音、词义词性和词性变化及例句
def query_youdao(word):
# 构造有道词典的查询网址
url = "http://dict.youdao.com/w/" + word
# 发送请求,获取网页内容
response = requests.get(url)
# 解析网页内容,使用html.parser作为解析器
soup = BeautifulSoup(response.text, "html.parser")
# 查找读音所在的标签,使用find方法,根据class属性筛选
phonetic = soup.find(class_="phonetic")
# 如果找到了读音标签,就提取其中的文本,否则返回空字符串
if phonetic:
phonetic = phonetic.text
else:
phonetic = ""
# 查找词义词性所在的标签,使用find_all方法,根据li标签筛选
meanings = soup.find_all("li")
# 定义一个空列表,用于存储词义词性
meaning_list = []
# 遍历每个li标签,提取其中的文本,并添加到列表中
for meaning in meanings:
meaning_list.append(meaning.text)
# 将列表转换为字符串,用换行符分隔每个元素
meaning_str = "\n".join(meaning_list)
# 查找词性变化所在的标签,使用find方法,根据class属性筛选
variations = soup.find(class_="additional")
# 如果找到了词性变化标签,就提取其中的文本,并去掉多余的空格和换行符,否则返回空字符串
if variations:
variations = variations.text.strip().replace("\n", " ")
else:
variations = ""
# 查找例句所在的标签,使用find方法,根据id属性筛选
sentences = soup.find(id="bilingual")
# 如果找到了例句标签,就提取其中的文本,并去掉多余的空格和换行符,否则返回空字符串
if sentences:
sentences = sentences.text.strip().replace("\n", " ")
else:
sentences = ""
# 返回读音、词义词性、词性变化和例句组成的元组
return (phonetic, meaning_str, variations, sentences)
# 测试函数,查询单词"python"
Input_Word = input("请输入要查询的单词:(单词用'/'分开)")
list_word = Input_Word.split('/')
for lst in list_word:
result = query_youdao(lst)
# 打印结果
with open('words.txt','a+',encoding="UTF-8") as f:
for word in result:
f.write(lst)
f.write(word)
f.write('\n\n')
print(result)