多个索引答案Python 3

时间:2019-02-17 02:55:04

标签: python python-3.x

我有一个程序,用户可以在其中输入单词,然后通过刮擦DuckDuckGo的自动响应框来在其前面打印定义。

import requests
import sys
import codecs
import os
import time
def end():
    steve = 1
p1 = "https://duckduckgo.com/?q="
p2 = input().replace(" ", "+")
p3 = p1 + p2
timeout = 0
def find():
    global timeout
    timeout += 1
    print(timeout)
    try:
        time.sleep(1)
        res = requests.get(p3)
        res.raise_for_status()
        playFile = open('RomeoAndJuliet1.txt', 'wb')
        for chunk in res.iter_content(100000):
            playFile.write(chunk)

        playFile.close()

        f = codecs.open('RomeoAndJuliet1.txt',encoding='utf-8')
        contents = f.read()
        newcontents = contents.replace('"','*').replace("'", '^')
        page = newcontents
        i = page.index("Abstract") + 11 
        defn = page[i: page.index("*", i)]
        f.close
        if timeout == 8:
            print('timed out')
            exit()
        if defn == '' or defn == 't' or defn == 'rce':
            find()
        if defn != '' or defn != 't' or defn != 'rce' or defn != 'err':
            open("demofile.txt", "w").write(defn)
            print(defn)
            end()
    except:
            print('err')
            end()
find()
end()
os.remove("RomeoAndJuliet1.txt")

有时,我会得到tsrc的不必要的定义,或者只是一个空白字符。我已通过使程序重新加载页面并再次检查来进行调整。

我的主要问题是,当程序必须刷新时,它会输出预期的答案以及上面列出的所有不需要的答案。

>>> 
== RESTART==
bill gates
1 #Number of refresh attempts
2
3
William Henry Gates III is an American business magnate, investor, author, philanthropist, humanitarian, and principal founder of Microsoft Corporation. During his career at Microsoft, Gates held the positions of chairman, CEO and chief software architect, while also being the largest individual shareholder until May 2014.
rce
rce
>>> 

我试图只获得预期的答案并将其存储在文本文件中,但是它总是被不需要的答案覆盖

1 个答案:

答案 0 :(得分:4)

我改变了

if defn != '' or defn != 't' or defn != 'rce' or defn != 'err':
        open("demofile.txt", "w").write(defn)
        print(defn)
        end()

if defn != '' and defn != 't' and defn != 'rce' and defn != 'err':
        open("demofile.txt", "w").write(defn)
        print(defn)
        end()

我只将or更改为and

现在demofile.txt包含预期的答案,并且只有在defn不等于特定值的情况下才会执行此部分

由于两个原因,文件被覆盖。

  • 第一个原因是您将or!=结合使用,因此当满足一个!=条款时,自defn以来总是如此不能同时执行所有操作,否则将执行if部分。

  • 第二个原因是您在以下位置在find()中调用find():

    if defn == '' or defn == 't' or defn == 'rce':
            find()
    

    自从出现之前:

    if defn != '' and defn != 't' and defn != 'rce' and defn != 'err':
            open("demofile.txt", "w").write(defn)
            print(defn)
            end()
    

    在第一次致电find()后未能返回预期的答案后,它将随后呼叫find(),后者(可能)会再次呼叫find(),依此类推,直到预期的为止这些find()呼叫之一将返回答案,从而结束连续的find()呼叫。然后,“失败的” find()呼叫将覆盖“正确的” find()呼叫答案,因为在“正确”的find()呼叫完成后,其他find()呼叫以相反的顺序执行,它们最初被调用,直到到达各个函数的各个末端为止。