我要计算的是在goole第一页结果站点上特定单词的出现次数,然后再次计算另一个单词-如果该单词出现两次以上,那么我将更改第一个单词的出现次数到0。但是我得到这个错误:
文件“ D:\ HQ_Bot-master \ answer_bot.py”,第307行,在 get_points_live()
文件“ D:\ HQ_Bot-master \ answer_bot.py”,第293行,位于get_points_live中 points,maxo = google_wiki(simq,options,neg)
google_wiki中的文件“ D:\ HQ_Bot-master \ answer_bot.py”,第242行 count2 = len(words2)
TypeError:类型为'NoneType'的对象没有len()
这是我的代码:
import string
import requests
import json
import urllib.request as urllib2
from bs4 import BeautifulSoup
from google import google
from PIL import Image
import pytesseract
import argparse
import cv2
import os
import pyscreenshot as Imagegrab
import sys
import wx
from halo import Halo
def google_wiki(sim_ques, options, neg):
spinner = Halo(text='Googling and searching Wikipedia', spinner='dots2')
spinner.start()
num_pages = 1
points = list()
content = ""
maxo=""
maxp=-sys.maxsize
i = 0
temp = 0
ques = ""
translator = str.maketrans(string.punctuation, ' '*len(string.punctuation))
sim_ques22 = sim_ques.translate(translator)
while i < 3:
o = options[i]
if i <= 1:
x = options[i+1]
else:
x = options[i-1]
o = o.lower()
x = x.lower()
ques += sim_ques22 + ' ' + o + ' wiki'
print(ques)
page = requests.get("http://www.google.com/search?q="+ques)
soup = BeautifulSoup(page.text,"lxml")
words = soup.find(text=lambda text: text and o in text)
if(type(words)is not None):
count = len(words)
words2 = soup.find(text=lambda text: text and x in text)
if(type(words)is not None):
count2 = len(words2)
if count2 >= 2:
temp = 0
else:
temp = count
if neg:
temp*=-1
points.append(temp)
if temp>maxp:
maxp=temp
maxo=o
ques = ""
i += 1
spinner.succeed()
spinner.stop()
return points,maxo
答案 0 :(得分:0)
您可以使用简单的三元语句:
count = len(words) if words else 0
与此相同
if words: # This checks if it is truthy (which None is not)
count = len(words)
else:
count = 0
如果需要,可以将条件替换为if words is None
。
编辑:稍后您使用变量时,我使用了三元表达式。否则,您将得到NameError
。
答案 1 :(得分:0)
只需尝试使用try,除非您想继续但不出现错误或捕获错误并在需要时打印
try:
// your code where you got the error
except:
pass
// or print the error caught if you want