0

我正在编写一个脚本,该脚本将使用 DuckDuckGo 抓取我的问题的任何答案!我尝试使用 DuckDuckGo 的 API 执行此操作,它也可以正常工作,但结果提供了大量信息。有没有什么方法可以限制它的句子?喜欢3句还是4句?这是我到目前为止的脚本:

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 个句子。)

4

1 回答 1

0

例如,如果你想限制相关主题的数量,你可以使用这样的东西:

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 个相关主题:

{'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...'}
于 2021-11-25T14:43:34.270 回答