首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Python编辑DuckDuckGo中显示的句子数量?

如何使用Python编辑DuckDuckGo中显示的句子数量?
EN

Stack Overflow用户
提问于 2021-11-23 21:21:14
回答 1查看 30关注 0票数 0

我正在编写一个脚本,它将使用DuckDuckGo抓取我的问题的所有答案!我试着使用DuckDuckGo的API来做这件事,它也能工作,但结果给出了大量的信息。有没有办法限制它的句子?像是三句话还是四句话?这是我到现在为止的脚本:

代码语言:javascript
复制
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"])

我得到了什么输出:

代码语言:javascript
复制
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句)。

EN

回答 1

Stack Overflow用户

发布于 2021-11-25 14:43:34

例如,如果您想限制RelatedTopics计数,可以使用如下命令:

代码语言:javascript
复制
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:

代码语言:javascript
复制
{'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...'}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70087977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档