我正在编写一个脚本,它将使用DuckDuckGo抓取我的问题的所有答案!我试着使用DuckDuckGo的API来做这件事,它也能工作,但结果给出了大量的信息。有没有办法限制它的句子?像是三句话还是四句话?这是我到现在为止的脚本:
word = input("Enter the Word: ")
query = f"what is {word}?"
r = requests.get("https://api.duckduckgo.com",
params = {
"q": query,
"format": "json"
})
data = r.json()
print(data["Abstract"])我得到了什么输出:
Enter the Word: Artificial Intelligence
Artificial intelligence is intelligence demonstrated by machines, as opposed to natural intelligence displayed by animals including humans. Leading AI textbooks define the field as the study of "intelligent agents": any system that perceives its environment and takes actions that maximize its chance of achieving its goals. Some popular accounts use the term "artificial intelligence" to describe machines that mimic "cognitive" functions that humans associate with the human mind, such as "learning" and "problem solving", however, this definition is rejected by major AI researchers. AI applications include advanced web search engines, recommendation systems, understanding human speech, self-driving cars, automated decision-making and competing at the highest level in strategic game systems. As machines become increasingly capable, tasks considered to require "intelligence" are often removed from the definition of AI, a phenomenon known as the AI effect.我希望它只打印开始的几句话(即:只打印前3或4句)。
发布于 2021-11-25 14:43:34
例如,如果您想限制RelatedTopics计数,可以使用如下命令:
def limit_count_topicks(n):
for i in range(len(data['RelatedTopics'])):
if i == n:
break
print(data['RelatedTopics'][i])
limit_count_topicks(2)仅输出2个相关的topicks:
{'FirstURL': 'https://duckduckgo.com/Happiness', 'Icon': {'Height': '', 'URL': '/i/a62c4a70.png', 'Width': ''}, 'Result': '<a href="https://duckduckgo.com/Happiness">Happiness</a>The term happiness is used in the context of mental or emotional states, including positive or...', 'Text': 'Happiness The term happiness is used in the context of mental or emotional states, including positive or...'}
{'FirstURL': 'https://duckduckgo.com/Happy!_(TV_series)', 'Icon': {'Height': '', 'URL': '', 'Width': ''}, 'Result': '<a href="https://duckduckgo.com/Happy!_(TV_series)">Happy! (TV series)</a>Happy! is an American live-action/adult animated black comedy/action-drama television series...', 'Text': 'Happy! (TV series) Happy! is an American live-action/adult animated black comedy/action-drama television series...'}https://stackoverflow.com/questions/70087977
复制相似问题