gpt4 book ai didi

python - 多索引答案 Python 3

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:13 25 4
gpt4 key购买 nike

我有一个程序,用户可以在其中输入他们的单词,然后他们会通过抓取 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
>>>

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

最佳答案

我变了

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()

我只将更改为

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

文件被覆盖有两个原因。

  • 第一个原因是您将 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() 调用将以与它们最初被调用的顺序相反的顺序执行,直到到达各自函数的各自末端。

关于python - 多索引答案 Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com