排行榜

  • 用户榜
  • 标签榜
  • 冲榜分奖金

频道

最新最热悬赏待采纳 筛选
  • 0

    回答

  • 16

    浏览

#! -*- coding:utf-8 -*- #from __future__ import division import sys from importlib import reload reload(sys) # sys.setdefaultencoding('utf8') import os import re StopWordtmp = [' ', u'\u3000', u'\u3001', u'\u300a', u'\u300b', u'\uff1b', u'\uff02', u'\u30fb', u'\u25ce', u'\x30fb',                u'\u3002', u'\uff0c', u'\uff01', u'\uff1f', u'\uff1a', u'\u201c', u'\u201d', u'\u2018', u'\u2019',                u'\uff08', u'\uff09', u'\u3010', u'\u3011', u'\uff5b', u'\uff5d', u'-', u'\uff0d', u'\uff5e', u'\uff3b',                u'\uff3d', u'\u3014', u'\u3015', u'\uff0e', u'\uff20', u'\uffe5', u'\u2022', u'.'] WordDic = {} StopWord = [] StatisticDic = {} span = 16 # 将停用词读入列表 def InitStopword():     for key in StopWordtmp:         StopWord.append(key) def InitDic(Dicfile):     f = open(Dicfile,encoding='utf8')     for line in f:         # line = line.strip().decode('utf-8')         line = line.strip()         WordDic[line] = 1;     f.close()     # print len(WordDic)     # print "Dictionary has built down!" def InitStatisticDic(StatisticDicfile):     StatisticDic['<BEG>'] = {}     f = open(StatisticDicfile,encoding='utf8')     for line in f:         # chunk = line.strip().decode('utf-8').split('  ')         chunk = line.strip().split('  ')         if chunk[0] != '':             if chunk[0] not in StatisticDic['<BEG>']:                 StatisticDic['<BEG>'][chunk[0]] = 1             else:                 StatisticDic['<BEG>'][chunk[0]] += 1         for i in range(len(chunk) - 1):             # if not StatisticDic.has_key(chunk[i]) and chunk[i] != '':             if chunk[i] not in StatisticDic and chunk[i] != '':                 StatisticDic[chunk[i]] = {}             if chunk[i] != '':                 if chunk[i + 1] not in StatisticDic[chunk[i]]:                     StatisticDic[chunk[i]][chunk[i + 1]] = 1                 else:                     StatisticDic[chunk[i]][chunk[i + 1]] += 1         if chunk[-1] not in StatisticDic and chunk[-1] != '':             StatisticDic[chunk[-1]] = {}         if chunk[-1] != '':             if '<END>' not in StatisticDic[chunk[-1]]:                 StatisticDic[chunk[-1]]['<END>'] = 1             else:                 StatisticDic[chunk[-1]]['<END>'] += 1 def WordSeg(Inputfile, Outputfile):     f = open(Inputfile,encoding='utf8')     w = open(Outputfile, 'w',encoding='utf8')     dic_size = 0     for key in StatisticDic:         for keys in StatisticDic[key]:             dic_size += StatisticDic[key][keys]     for line in f:         line = line.strip()         senList = []         newsenList = []         tmpword = ''         for i in range(len(line)):             if line[i] in StopWord:                 senList.append(tmpword)                 senList.append(line[i])                 tmpword = ''             else:                 tmpword += line[i]                 if i == len(line) - 1:                     senList.append(tmpword)         # N-gram         for key in senList:             if key in StopWord:                 newsenList.append(key)             else:                 Pretmplist = PreSenSeg(key, span)                 Posttmplist = PostSenSeg(key, span)                 tmp_pre = P(Pretmplist, dic_size)                 tmp_post = P(Posttmplist, dic_size)                 tmplist = []                 if tmp_pre > tmp_post:                     tmplist = Pretmplist                 else:                     tmplist = Posttmplist                 # print 'tmplist', tmplist                 for keyseg in tmplist:                     newsenList.append(keyseg)         writeline = ''         for key in newsenList:             writeline = writeline + key + '  '         writeline = writeline.strip('  ')         w.write(writeline + '\n')     # break     f.close()     w.close() # 根据概率的乘法定理及N-gram模型,字串出现的概率 def P(tmplist, dic_size):     rev = 1     if len(tmplist) < 1:         return 0     '''     print 'tmplist', tmplist     print "tmplist[0]", tmplist[0]     print '-----------'     '''     rev *= Pword(tmplist[0], '<BEG>', dic_size)     rev *= Pword('<END>', tmplist[-1], dic_size)     for i in range(len(tmplist) - 1):         a = Pword(tmplist[i + 1], tmplist[i], dic_size)         rev *= a     return rev # 基于N-gram模型,用字在语料库中出现频率来估计 # ??????????????????????????????????? def Pword(word1, word2, dic_size):     # print 'word1:', word1     # print 'word2:', word2     div_up = 0     div_down = 0     if word2 in StatisticDic:         for key in StatisticDic[word2]:             # print 'key:', key·             div_down += StatisticDic[word2][key]     #??????             if key == word1:                 div_up = StatisticDic[word2][key]     return (div_up + 1) / (div_down + dic_size)  # 平滑技术??? def PreSenSeg(sen, span):     # sen = u"北京奥运"     post = span     if len(sen) < span:         post = len(sen)     cur = 0     revlist = []     while 1:         if cur >= len(sen):             break         s = re.search(             u"^[0|1|2|3|4|5|6|7|8|9|\uff11|\uff12|\uff13|\uff14|\uff15|\uff16|\uff17|\uff18|\uff19|\uff10|\u4e00|\u4e8c|\u4e09|\u56db|\u4e94|\u516d|\u4e03|\u516b|\u4e5d|\u96f6|\u5341|\u767e|\u5343|\u4e07|\u4ebf|\u5146|\uff2f]+",             sen[cur:])         if s:             if s.group() != '':                 revlist.append(s.group())             cur = cur + len(s.group())             post = cur + span             if post > len(sen):                 post = len(sen)         s = re.search(             u"^[a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|\uff41|\uff42|\uff43|\uff44|\uff45|\uff46|\uff47|\uff48|\uff49|\uff47|\uff4b|\uff4c|\uff4d|\uff4e|\uff4f|\uff50|\uff51|\uff52|\uff53|\uff54|\uff55|\uff56|\uff57|\uff58|\uff59|\uff5a|\uff21|\uff22|\uff23|\uff24|\uff25|\uff26|\uff27|\uff28|\uff29|\uff2a|\uff2b|\uff2c|\uff2d|\uff2e|\uff2f|\uff30|\uff31|\uff32|\uff33|\uff35|\uff36|\uff37|\uff38|\uff39|\uff3a]+",             sen[cur:])         if s:             if s.group() != '':                 revlist.append(s.group())             cur = cur + len(s.group())             post = cur + span             if post > len(sen):                 post = len(sen)         if (sen[cur:post] in WordDic) or (cur + 1 == post):             if sen[cur:post] != '':                 revlist.append(sen[cur:post])             cur = post             post = post + span             if post > len(sen):                 post = len(sen)         else:             post -= 1     return revlist # def freq() def PostSenSeg(sen, span):     cur = len(sen)     pre = cur - span     if pre < 0:         pre = 0     revlist = []     while 1:         if cur <= 0:             break         s = re.search(             u"[0|1|2|3|4|5|6|7|8|9|\uff11|\uff12|\uff13|\uff14|\uff15|\uff16|\uff17|\uff18|\uff19|\uff10|\u4e00|\u4e8c|\u4e09|\u56db|\u4e94|\u516d|\u4e03|\u516b|\u4e5d|\u96f6|\u5341|\u767e|\u5343|\u4e07|\u4ebf|\u5146|\uff2f]+$",             sen[pre:cur])         if s:             if s.group() != '':                 revlist.append(s.group())             cur = cur - len(s.group())             pre = cur - span             if pre < 0:                 pre = 0         s = re.search(             u"^[a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|\uff41|\uff42|\uff43|\uff44|\uff45|\uff46|\uff47|\uff48|\uff49|\uff47|\uff4b|\uff4c|\uff4d|\uff4e|\uff4f|\uff50|\uff51|\uff52|\uff53|\uff54|\uff55|\uff56|\uff57|\uff58|\uff59|\uff5a|\uff21|\uff22|\uff23|\uff24|\uff25|\uff26|\uff27|\uff28|\uff29|\uff2a|\uff2b|\uff2c|\uff2d|\uff2e|\uff2f|\uff30|\uff31|\uff32|\uff33|\uff35|\uff36|\uff37|\uff38|\uff39|\uff3a]+",             sen[pre:cur])         if s:             if s.group() != '':                 revlist.append(s.group())             cur = cur - len(s.group())             pre = cur - span             if pre < 0:                 pre = 0         if (sen[pre:cur] in WordDic) or (cur - 1 == pre):             if sen[pre:cur] != '':                 revlist.append(sen[pre:cur])             cur = pre             pre = pre - span             if pre < 0:                 pre = 0         else:             pre += 1     return revlist[::-1] if __name__ == "__main__":     # if len(sys.argv) != 5:     #  print("Usage: python wordseg.py Dicfile Inputfile Outfile")     Dicfile = r'D:\pythonProject\Ngram\dic.txt'  # sys.argv[1]     StatisticDicfile = r'D:\pythonProject\Ngram\traindata.txt'  # sys.argv[2]     Inputfile = r'D:\pythonProject\Ngram\test.txt'  # sys.argv[3]     Outputfile = r'D:\pythonProject\Ngram\out1.txt'  # sys.argv[4]     InitDic(Dicfile)     InitStatisticDic(StatisticDicfile)     # print "Dic:", StatisticDic     InitStopword()     WordSeg(Inputfile, Outputfile)  

  • 0

    回答

  • 11

    浏览

做了一个简单的UDP服务器,其中有一部分:套接字1接收到addr1发来的数据,用套接字2发送信息到addr1,现在的问题是addr1处收不到信息 s1 = socket.socket(socket.AF_INET, socket.SOCK_DRGAM) s2 = socket.socket(socket.AF_INET, socket.SOCK_DRGAM) s1.bind("0.0.0.0", 12345) # s1接收 data, addr = s1.recvfrom(1024) # s2发送到addr s2.sendto(b'OK', addr) 如果是同一个套接字可以正常收发(如下) s = socket.socket(socket.AF_INET, socket.SOCK_DRGAM) s.bind("0.0.0.0", 12345) data, addr = s.recvfrom(1024) s.sendto(b'OK', addr) 为什么上面的就不行呢?

  • 4

    回答

  • 24

    浏览

import requests from lxml import etree from time import sleep from fake_useragent import UserAgent import pandas as pd name_all = [] min_price_all = [] mean_price_all = [] max_price_all = [] guige_all = [] unit_all = [] data_all = [] for i in range(5): print(i) UA = UserAgent().edge url_base='http://www.xinfadi.com.cn/marketanalysis/0/list/{}.shtml' url = 'http://www.xinfadi.com.cn/marketanalysis/0/list/{}.shtml'.format(i+1) headers={ 'User-Agent':UA } response=requests.get(url,headers=headers) sleep(3) # print(response.text) # print(response.encoding) e = etree.HTML(response.text) name = e.xpath('''//table[@class='hq_table']/tr[position()>1]/td[1]/text()''') min_price = e.xpath('''//table[@class='hq_table']/tr[position()>1]/td[2]/text()''') mean_price = e.xpath('''//table[@class='hq_table']/tr[position()>1]/td[3]/text()''') max_price = e.xpath('''//table[@class='hq_table']/tr[position()>1]/td[4]/text()''') guige = e.xpath('''//table[@class='hq_table']/tr[position()>1]/td[5]/text()''') unit = e.xpath('''//table[@class='hq_table']/tr[position()>1]/td[6]/text()''') data = e.xpath('''//table[@class='hq_table']/tr[position()>1]/td[7]/text()''') name_all = name_all+name min_price_all = min_price_all+min_price mean_price_all = mean_price_all+mean_price max_price_all=max_price_all+max_price guige_all = guige_all+guige unit_all = unit_all+unit data_all=data_all+data if i % 300 == 0: all_info = { '名称': name_all, '最低价格': min_price_all, '平均价格': mean_price_all, '最高价格': max_price_all, '规格': guige_all, '单位':unit_all, '日期':data_all } outdata = pd.DataFrame(all_info) print(outdata) #outdata.to_csv('C:\\Users\geng\Desktop\蔬菜价格数据\新发地市场价格.csv', encoding='GBK') 上面这个是在网上找到的一段爬取蔬菜价格的代码,只能爬取第一页的数据,无法实现翻页 import requests #用来发送请求 from bs4 import BeautifulSoup#用来解析网页 import time#导入时间隔 import codecs with open('新发地果蔬价格.csv','wb+') as cf: cf.write(codecs.BOM_UTF8) for i in range(5):#爬取第一页到第100页的数据 f = open("新发地果蔬价格.csv",mode='a',encoding="utf8")#写人文件新发地果蔬文件名,格式是csv.字符编码,a是文字 resp = requests.get(f"http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml") print(resp)#200: ok, 302:重定向, 404:页面丢失,500:服务器错误 page_one = BeautifulSoup(resp.text, "html.parser")#通过html来,把请求的网页打印出来 #找到表格数据(table) table = page_one.find("table",attrs={"class":"hq_table"}) #表格特征是class和hq_table #找到所有表格的所有tr trs = table.find_all("tr")[1:]#获取表格的内容,通过列表来,第0个元素不要了,[第一行,第二行,到三行...... for tr in trs:#tr是每一行内容,在所有的行中,遍历每一列的内容 tds = tr.find_all("td")#tds是每一列的内容,[第一列,第二列,第三列......] name = tds[0].text.strip()#从第0项元素开始取值,取文本形式的内容数据,strip去掉左右两边所有的空格 lowest = tds[1].text.strip()#获取到数据,去掉左右空格 avg = tds[2].text.strip()#获取平均价数据,去掉左右空格 highest = tds[3].text.strip()#获取最高价,去掉左右空格 fenlei = tds[4].text.strip()#获取分类,去掉左右的空格 danwei = tds[5].text.strip()#获取单位数据,去掉左右的空格 date = tds[6].text.strip()#获取日期数据,去掉左右空ge f.write(f"{name},{lowest},{avg},{highest},{fenlei},{danwei},{date}\n")#把每种果蔬的名字.日期,价格写入,且换行 #print(f"{name},{lowest},{avg},{highest},{fenlei},{danwei},{date}") print(f"一个页面完事了{i}") time.sleep(1)#防止服务器蹦了,间隔一秒钟 这是另一段代码,功能相同,也是无法翻页爬取,请问怎么才能翻页爬取内容

  • 3

    回答

  • 28

    浏览

如何将课程名称全部修改为体育A  

  • 5

    回答

  • 34

    浏览

随机输入一个字符串,计算这个字符串所有数字之和,如果字符串中无数字,输出结果为0 小白提问,老师布置的作业,拜托各位大佬了

  • 4

    回答

  • 19

    浏览

  • 2

    回答

  • 8

    浏览

我是在Windows上训练好模型后,用tensorflow.keras.models的load_model方法来加载在Windows上训练得到的模型,请问也是这样解决吗?

  • 2

    回答

  • 18

    浏览

有没有大佬能解决这个问题,在此跪谢"Traceback (most recent call last):   File "E:/work/Remote-sensing-master/Remote-sensing-master/Remote-sensing-master/model.py", line 168, in <module>     k = model.predict(img_tensor,)   File "E:\Anaconda\lib\site-packages\keras\engine\training.py", line 1149, in predict     x, _, _ = self._standardize_user_data(x)   File "E:\Anaconda\lib\site-packages\keras\engine\training.py", line 751, in _standardize_user_data     exception_prefix='input')   File "E:\Anaconda\lib\site-packages\keras\engine\training_utils.py", line 138, in standardize_input_data     str(data_shape)) ValueError: Error when checking input: expected conv2d_1_input to have shape (120, 120, 3) but got array with shape (60, 60, 4)" 以下是代码: from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D from keras.layers import Activation, Dropout, Flatten, Dense from keras.preprocessing.image import ImageDataGenerator from keras.optimizers import rmsprop from PIL import Image import numpy as np from keras.preprocessing import image n_classes = 3 model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),                  activation='relu',                  input_shape=(120, 120, 3))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(3, activation='softmax')) model.compile(optimizer = rmsprop(lr=0.0001, decay=1e-6),                    loss = 'categorical_crossentropy',                     metrics = ['accuracy']) batch_size = 16 #batch_size = 128 train_datagen = ImageDataGenerator(         rescale = 1./255,         shear_range=0.2,         zoom_range=0.2,         horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory(         'dataset/train',         target_size=(120, 120),         batch_size = 16,         class_mode='categorical') validation_generator = test_datagen.flow_from_directory(         'dataset/validation',         target_size=(120, 120),         batch_size=16,         class_mode = 'categorical') # model.fit_generator(         train_generator,         steps_per_epoch=701 // 16,         epochs = 8,         validation_data=validation_generator,         validation_steps= 79 // 16         ) #validation_steps= 800 // 128 sample_shape = 60 test_image = Image.open('dataset/530m_2_copy.png') #width, height = test_image.size box = (0, 0, sample_shape, sample_shape) width = test_image.size[0] height = test_image.size[1] print(width,height) for x in range(0, width, 3):     for y in range(0, height, 3):         if x + sample_shape < width:             x2 = x + sample_shape         else:             break         if y + sample_shape < height:             y2 = y + sample_shape         else:             break         box = (x, y, x2, y2)         sample = test_image.crop(box)         img = sample         img_tensor = image.img_to_array(img)         img_tensor = np.expand_dims(img_tensor, axis=0)         img_tensor /= 255. k = model.predict(img_tensor,) print(k)

  • 1

    回答

  • 11

    浏览

C:\Users\Administrator\AppData\Local\Programs\Python\Python39\python.exe D:/pythonProject/practice.py multiple 'pyface.toolkits' plugins found for toolkit 'qt4': pyface.ui.qt4.init, pyface.ui.qt4.init Traceback (most recent call last):   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\vtkmodules\__init__.py", line 13, in <module>     from . import vtkCommonCore ImportError: cannot import name 'vtkCommonCore' from partially initialized module 'vtkmodules' (most likely due to a circular import) (C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\vtkmodules\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last):   File "D:\pythonProject\practice.py", line 1, in <module>     import mayavi.mlab   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\mayavi\mlab.py", line 16, in <module>     from mayavi.tools.camera import view, roll, yaw, pitch, move   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\mayavi\tools\camera.py", line 24, in <module>     from .engine_manager import get_engine   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\mayavi\tools\engine_manager.py", line 13, in <module>     from mayavi.core.registry import registry   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\mayavi\core\registry.py", line 16, in <module>     from mayavi.core.metadata import Metadata, import_symbol   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\mayavi\core\metadata.py", line 11, in <module>     from mayavi.core.pipeline_info import PipelineInfo   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\mayavi\core\pipeline_info.py", line 12, in <module>     from .utils import get_tvtk_dataset_name   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\mayavi\core\utils.py", line 2, in <module>     import vtk   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\vtk.py", line 30, in <module>     all_m = importlib.import_module('vtkmodules.all')   File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module     return _bootstrap._gcd_import(name[level:], package, level)   File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\vtkmodules\__init__.py", line 15, in <module>     import _vtkmodules_static ModuleNotFoundError: No module named '_vtkmodules_static' Process finished with exit code 1    

  • 1

    回答

  • 14

    浏览

跪求大神专家给小白解答0.0: 习题三 编写函数,使用递归方法求 C(n, k) 。 习题四 编写函数,计算圆周率。存在圆心在直角坐标系原点且半径为 1 的圆及其外切正方形。为计算方便,仅考虑位于第一象限的四分之一正方形和四分之一圆。随机生成该四分之一正方形中一系列点,散布于四分之一圆内比例即为圆周率四分之一。散步点越多,结果越精确,耗时也越长。

  • 2

    回答

  • 12

    浏览

在pip已经安装了baidu-aip的模块 但在pycharm中用import导入aip就爆红 有没有大佬知道咋解决

  • 3

    回答

  • 27

    浏览

我在一台电脑上运行服务端和客户端,成功。但把客户端放到另外一台电脑上的安卓模拟器里,就出错。我传送的只是一些文字和数字而已,没有特殊字符。 我把服务端根据算法生成的文件变成JSON文件,切成1024大小,分多次发送。 当8次发送的时候(一个小点的数据流),完全正常。当13次发送的时候(另外一个大一点的数据流),就出现故障了。 adb现在乱码,看不到接收到的JSON是怎样的,但根据没乱码之前的经验,应该是不完整的。 我在接收recv这块,做的是while循环,当收到的数据为0的时候,则中断接收。我设定的是recv(20480),正常的那个是接收了2次(服务端发送了8次 1024),有故障的那个是接收了3次(服务端发送了13次1024)。我在客户端设置了 RECV_BUF_SIZE = 204800。 没有做切片发送的时候,做了尾标识方法的接收方法,但也不好使。 请问这是什么问题,该如何解决?

回答 樱桃爸爸
采纳率33.3%
6小时前
  • 1

    回答

  • 27

    浏览

小白求救,我写了一个从数据库中读取url地址后通过爬虫下载图片到本地后在程序上实时显示出来的功能,但是一刷新后界面会卡死,上网搜了一下是我把数据读取和显示功能写在同一线程下,需要用到Qthread多线程实现,但网上搜到的实例对我的帮助还是比较有限,想问问大佬们该怎么实现,代码如下: import os from screen import * from PyQt5 import QtWidgets from PyQt5.QtCore import QTimer, QDateTime from PyQt5.QtGui import QImage,QPixmap,QStandardItem from PyQt5.QtWidgets import QGraphicsPixmapItem,QGraphicsScene import cv2 from Img import get_img class MainController(QtWidgets.QMainWindow,Ui_MainWindow): def __init__(self): super(MainController, self).__init__() # self.thread = Worker() self.setupUi(self) self.showImage('image/init.jpg',600) self.timer = QTimer() self.timer.timeout.connect(self.showTime) self.timer.start(1000) def display(self,data): if "name" in data: self.Assembly.setText(data["name"]) response = get_img(data['name']) if response == 2: self.help.hide() else: path = os.path.abspath('./image') +'\\'+ data['name'] + '.jpg' self.showImage(path,600) if "order_num" in data: self.label_4.setText(data["order_num"]) if "p_code" in data: self.label_6.setText(data["p_code"]) if "p_name" in data: self.label_9.setText(data["p_name"]) if "total" in data: self.label_8.setText(data["total"]) if "p_number" in data: self.p_number.setText(data["p_number"]) if "BOM" in data: bom = data["BOM"] self.init_table(bom) if "STEP" in data: step = data["STEP"] self.init_step_table(step) def showTitle(self,tt): self.Assembly.setText(tt) def showLogo(self,logo): self.label.setText(logo) def showTime(self): time = QDateTime.currentDateTime() timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd") self.showtime.setText(timeDisplay) def closeEvent(self, event): os._exit(0) def show_selected_image(self, imageFile): try: image = cv2.imread(imageFile) # 读取图像 image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) height = image.shape[0] width = image.shape[1] self.zoomscale = 1 frame = QImage(image, width, height, QImage.Format_RGB888) pix = QPixmap.fromImage(frame) self.item = QGraphicsPixmapItem(pix) self.item.setScale(self.zoomscale) self.scene = QGraphicsScene() # 创建场景 self.scene.addItem(self.item) self.gview.setScene(self.scene) except Exception as e : print(e) def showImage(self,imageName,h): try: self.scaled_pixmap = QPixmap(imageName).scaledToHeight(h) self.image_lbl.setPixmap(self.scaled_pixmap) except Exception as e: print(e) def init_table(self,bom): try: self.HeaderList = ["编号"] self.HeaderList.append("名称") self.HeaderList.append("数量") self.DataModel = QtGui.QStandardItemModel() self.DataModel.setHorizontalHeaderLabels(self.HeaderList) # vr = bom.split("],[") i = 0 for v in vr: # print(v) v = v.replace("]","").replace("[","") d = v.split(",") self.DataModel.setItem(i, 0, QStandardItem(d[0])) self.DataModel.setItem(i, 1, QStandardItem(d[2])) self.DataModel.setItem(i, 2, QStandardItem(d[1])) i = i + 1 self.tableView.setModel(self.DataModel) self.tableView.verticalHeader().hide() self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) # self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) print(1) return True except Exception as e: print(e) def init_step_table(self, step): try: self.HeaderList.append("名称") self.HeaderList.append("指令") self.DataModel = QtGui.QStandardItemModel() self.DataModel.setHorizontalHeaderLabels(self.HeaderList) # vr = step.split("],[") i = 0 for v in vr: print(v) v = v.replace("]", "").replace("[", "") d = v.split(",") self.DataModel.setItem(i, 0, QStandardItem(d[0])) self.DataModel.setItem(i, 1, QStandardItem(d[1])) i = i + 1 self.tableView.setModel(self.DataModel) self.tableView.verticalHeader().hide() self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) # self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) return True except Exception as e: print(e) 其中response = get_img(data['name'])中的get_img方法代码如下: import psycopg2 import requests import re import os find_csrf_token = re.compile(r'.*"csrf_token" value="(.*?)"') find_img = re.compile(r'<img.*src="(.*?)"') def get_img(name): session = requests.Session() url = 'XXXXXXXXXX' second_url = 'XXXXXXXXXXXXXX' header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'} session.get(url, headers=header) s_response = session.get(url=second_url, headers=header) result = re.findall(find_csrf_token, s_response.text) csrf_token = '' finnal = 'XXXXXXXXXXXXXXXX' header.update({'csrf_token': csrf_token}) session.post(finnal, headers=header) for i in result: csrf_token = i conn = psycopg2.connect(XXXXXXXXXXXXXXX) cursor = conn.cursor() sql =f"""select qp.note from quality_point qp inner join mrp_routing_workcenter mrw on qp.operation_id=mrw.id where qp.title='{name}'""" find_name =f"""select title from quality_point where title='{name}'""" cursor.execute(find_name) rename = cursor.fetchone() if rename: for i in rename: name = i cursor.execute(sql) list = cursor.fetchone() if list: list = str(list) response = re.findall(find_img,list) if response: for i in response: end = 'http://139.196.175.131:8069' + i link_jpg = session.get(end, headers=header) dir = os.path.abspath('./image') dir += '\\' + name + '.jpg' if os.path.exists(f"""./image/{name}.jpg"""): return 0 else: with open(dir, 'wb') as f: f.write(link_jpg.content) f.close() return 1 else: return 2 else: return 2  

  • 1

    回答

  • 9

    浏览

http -a admin:admin patch http://127.0.0.1:8000/api/article/8/ tags:='[\"java\"]' usage: http [--json] [--form] [--multipart] [--boundary BOUNDARY] [--compress] [--pretty {all,colors,format,none}] [--style STYLE] [--unsorted] [--sorted]             [--format-options FORMAT_OPTIONS] [--print WHAT] [--headers] [--body] [--verbose] [--all] [--history-print WHAT] [--stream] [--output FILE] [--download] [--continue] [--quiet]             [--session SESSION_NAME_OR_PATH | --session-read-only SESSION_NAME_OR_PATH] [--auth USER[:PASS]] [--auth-type {basic,digest}] [--ignore-netrc] [--offline]             [--proxy PROTOCOL:PROXY_URL] [--follow] [--max-redirects MAX_REDIRECTS] [--max-headers MAX_HEADERS] [--timeout SECONDS] [--check-status] [--path-as-is] [--chunked]             [--verify VERIFY] [--ssl {ssl2.3,tls1,tls1.1,tls1.2}] [--ciphers CIPHERS] [--cert CERT] [--cert-key CERT_KEY] [--ignore-stdin] [--help] [--version] [--traceback]             [--default-scheme DEFAULT_SCHEME] [--debug]             [METHOD] URL [REQUEST_ITEM [REQUEST_ITEM ...]] http: error: "tags:='["java"]'": Expecting value: line 1 column 1 (char 0)

  • 1

    回答

  • 12

    浏览

1,回归与渐度下降 (1)下列用python画出(-10<x<10)          y=4+5x+2x^2   (2)   将式子定义 parameter(a0,a1,a2),这个式子中random number(应用基于正规分布生成random number的函数,选择适当的分布值)利用50对 data set 用python画出          y=a0+a1x+a2x^2 (3)laest square 方式求出上面的parameter(实际计算利用python) (4)在parameter上用Gradient Descent方式表示恰当的定义cost function或lost function 在此基础上以Gradient Descent方式对parameter寻求update式 (5)请利用python填写如(2)所示的请求data set。以(4)方式请求parameter程序图标显示每张cost值在iteration中的变化(可以根据需要增加data set 数,hyperparameter适当选择) 2 回归适中与正规化 (1)第一题(2)问生成10对data set。下列应用 least square method 求出parameter(实际计算使用python) (2)利用 ridge regression,regularization,为了不让overfitting发生,重新解答(1)(尝试ridge term 的hyperparameter 从小到大的多种尝试) (3)(1)生产10000对data set 解答问题时,请考虑并解决使用何种方式合适。(  hint,least square method? any updata function?)

  • 2

    回答

  • 16

    浏览

(球球路过的朋友们帮帮我)我需要在树莓派上用python读取一个激光测距仪的数据。一开始使用的是USB转TTL连接的(一个USB转一路串口,叫E15-232),直接使用串口的read方法就能读取;然后换成使用FT4232H模来连接了(它也是支持USB转TTL的,只不过是一个USB转4路串口),就出现问题了:在读取几行数据后就会出现read failed: device reports readiness to read but returned no data错误。 不知道是哪里出现的问题。

  • 4

    回答

  • 23

    浏览

本人初学python爬虫,最近在学习中碰到一个问题始终没法解决,在此请教各位大神帮忙。谢谢!! 在学习爬取www.tianqi.com/guangzhou/3/下的天气详情时,碰到网页代码中有注释,其中的空气质量和风向、风力信息是需要提取出来的。查找了很多都不能成功。希望得到大家的帮助。具体如截图。  

  • 4

    回答

  • 29

    浏览

刚开始学Python,学到Categorical这里出了点问题,查了一圈貌似是因为Python版本不一样才会报错,但是并没有找到合适的解决方法,代码如下,请大神帮忙看看 Cut=pd.Series(["Fair","Good","Very Good","Premium","Ideal"]) Cut_Facor2=Cut.astype("category",categories=["Good","Fair","Very Good","Ideal","Premium"],ordered=True)    

  • 3

    回答

  • 20

    浏览

y=4+5x+2x^2  (-10<x<10) 用python画

  • 0

    回答

  • 17

    浏览

python的版本为3.7,xlwings的版本为0.23.1,pywin32版本为300,运行至sht_1.api.UsedRange.Rows.count,不执行不报错,调试时,程序也不结束,显示一直运行中。 ps: 我两台电脑。在家写好的代码,家里电脑可以运行。去公司电脑就不能运行。公司和家里的pycharm、python、xlwings、pywin32版本都一样。另外公司的电脑,打开程序调用的为EXCEL,安装的为2013版本(不安装EXCEL,运行会报错)。家里电脑安装的wps,未安装EXCEL。 代码如下: import xlwings as xw def jisuan_1 (): app = xw.App(visible=False, add_book=True) wb_1 = app.books.open('C:/Users/Administrator/Desktop/4yue.xls') #完成后替换成 path_1.get() sht_1=wb_1.sheets[0] print(sht_1) rows = sht_1.api.UsedRange.Rows.count # 总行数 cols = sht_1.api.UsedRange.columns.count # 总列数 print(rows)  

  • 3

    回答

  • 18

    浏览

def active_status(data): status = [] for i in range(18): #若本月没有消费 if data[i] == 0: if len(status) > 0: if status[i-1] == 'unreg': status.append('unreg') else: status.append('unactive') else: status.append('unreg') #若本月消费 else: if len(status) == 0: status.append('new') else: if status[i-1] == 'unactive': status.append('return') elif status[i-1] == 'unreg': status.append('new') else: status.append('active') return status purchase_stats = df_purchase.apply(active_status,axis=1) purchase_stats #返回结果 user_id 1 [new, unactive, unactive, unactive, unactive, ... 2 [new, unactive, unactive, unactive, unactive, ... 3 [new, unactive, return, active, unactive, unac... 4 [new, unactive, unactive, unactive, unactive, ... 5 [new, active, unactive, return, active, active... ... 23566 [unreg, unreg, new, unactive, unactive, unacti... 23567 [unreg, unreg, new, unactive, unactive, unacti... 23568 [unreg, unreg, new, active, unactive, unactive... 23569 [unreg, unreg, new, unactive, unactive, unacti... 23570 [unreg, unreg, new, unactive, unactive, unacti... Length: 23570, dtype: object df_purchase还是一个dataframe表格如下图(我的目的就是把下图的数字替换成一个个如"new"\"unreg"等的英文):  

  • 4

    回答

  • 20

    浏览

然后读取全国人口数据,在上图的四个部分分别绘制以下图形: (1)东北三省1990和2001年人口的条形图(并列横向); (2)浙江省、广东省历年人口变化的折线图; (3)1990年、1995年和2001年全国人口的三个箱型图; (4)2001年全国各省市人口的直方图(要求分8个区间)。 评分标准:正确,完整(图的各个要素),美观。

  • 3

    回答

  • 19

    浏览

发现加载了api_data.js文件,把所有接口都加载了,打开页面都要好几分钟。怎么优化

  • 4

    回答

  • 25

    浏览

from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup def getTitle(url):     try:         html=urlopen(url)     except HTTPError as e:         return None     try:         bsObj=BeautifulSoup(html.read(),"html.parser")         title=bsObj.h1     except AttributeError as e:         return None title=getTitle("https://mail.qq.com/")

回答 Thoth101
采纳率100%
22小时前
  • 4

    回答

  • 17

    浏览

(my_env) C:\Users\xc7036>pyradiomics usage: pyradiomics image|batch [mask] [Options] pyradiomics: error: the following arguments are required: {Image,Batch}FILE