单词词义、词性、例句查询python代码-输出结果更简洁

#单词查询、输出结果更简洁,一次可查多个单词、程序输出的例句比较多。
#查询到的单词写入到words.txt文件中
import requests
from bs4 import BeautifulSoup
def query(word):
    # 获取有道词典网页的HTML代码
    url = 'http://dict.youdao.com/w/%s' % word
    html = requests.get(url).text

    # 使用BeautifulSoup解析HTML代码,并获取单词读音、词义和词性及例句
    soup = BeautifulSoup(html, 'html.parser')
    phonetic = soup.find(class_='phonetic').get_text().strip()   # 获取单词的读音
    trans_container = soup.find(id='phrsListTab')   # 获取词义和例句的容器
    trans = trans_container.find(class_='trans-container').get_text().strip() # 获取词义
    examples = soup.find_all(class_='examples')  # 获取例句

    # 输出结果
    with open('words.txt', 'a+', encoding="UTF-8") as f:
        f.write(word+"\n")
        f.write(phonetic+"\n")
        f.write(trans+"\n")
        for example in examples:
            f.write(example.get_text().strip()+"\n")

    print('%s %s' % (word, phonetic))
    print(trans)
    print("-" * 30)
    print("例句:")
    for example in examples:
        print(example.get_text().strip())

 #输入要查询的英语单词
Input_Word = input("请输入要查询的单词(单词用'/'分开):")
list_word = Input_Word.split('/')
for lst in list_word:
    query(lst)

由cursor ai ide 编辑器生成的单词查询代码,只输出一个例句

# and extracts the text of the first "p" element within it.
# Here is the modified code to get the phonetic transcription, acceptation, part of speech, and example sentence of a word:
# # Import necessary libraries
import requests
from bs4 import BeautifulSoup

# Define the word to search for
word = "noise"

# Send a GET request to Youdao.com with the word as a parameter
response = requests.get(f"https://www.youdao.com/w/{word}/#keyfrom=dict2.top")

# Parse the HTML content of the response using BeautifulSoup
soup = BeautifulSoup(response.content, "html.parser")

# Find the phonetic transcription of the word
phonetic = soup.find("div", {"class": "baav"}).find("span", {"class": "pronounce"}).text

# Find the acceptation and part of speech of the word
acceptation = soup.find("div", {"class": "trans-container"}).find("ul").find("li").text

# Find an example sentence using the word
example = soup.find("div", {"class": "examples"}).find("p").text

# Print the phonetic transcription, acceptation, part of speech, and example sentence
print(f"Phonetic transcription: {phonetic}")
print(f"Acceptation and part of speech: {acceptation}")
print(f"Example sentence: {example}")