草庐IT

python - 类型错误 : a bytes-like object is required, 不是 'str'

以下是尝试使用套接字修改用户提供的输入的代码:fromsocketimport*serverName='127.0.0.1'serverPort=12000clientSocket=socket(AF_INET,SOCK_DGRAM)message=input('Inputlowercasesentence:')clientSocket.sendto(message,(serverName,serverPort))modifiedMessage,serverAddress=clientSocket.recvfrom(2048)print(modifiedMessage)clientSo

python - str.translate 给出 TypeError - Translate 接受一个参数(给定 2 个),在 Python 2 中工作

我有以下代码importnltk,os,json,csv,string,cPicklefromscipy.statsimportscoreatpercentilelmtzr=nltk.stem.wordnet.WordNetLemmatizer()defsanitize(wordList):answer=[word.translate(None,string.punctuation)forwordinwordList]answer=[lmtzr.lemmatize(word.lower())forwordinanswer]returnanswerwords=[]forfilenamei

python - Python 的字符串连接与 str.join 相比有多慢?

由于我对thisthread的回答中的评论,我想知道+=操作符和''.join()之间的速度差异是多少那么两者的速度比较呢? 最佳答案 发件人:EfficientStringConcatenation方法一:defmethod1():out_str=''fornuminxrange(loop_count):out_str+='num'returnout_str方法四:defmethod4():str_list=[]fornuminxrange(loop_count):str_list.append('num')return''.jo

Python 3 TypeError : must be str, not bytes with sys.stdout.write()

我正在寻找一种从python脚本运行外部进程并在执行期间打印其标准输出消息的方法。下面的代码有效,但在运行时不打印标准输出。当它退出时,我收到以下错误:sys.stdout.write(nextline)TypeError:mustbestr,notbytesp=subprocess.Popen(["demo.exe"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)#PollprocessfornewoutputuntilfinishedwhileTrue:nextline=p.stdout.readline()ifnextline=='

python - 什么是更快的操作,re.match/search 或 str.find?

对于一次性字符串搜索,简单地使用str.find/rfind是否比使用re.match/search更快?也就是说,对于给定的字符串s,我应该使用:ifs.find('lookforme')>-1:dosomething或ifre.match('lookforme',s):dosomethingelse? 最佳答案 问题:使用timeit最好回答哪个更快。fromtimeitimporttimeitimportredeffind(string,text):ifstring.find(text)>-1:passdefre_find(s

python - 如何连接 str 和 int 对象?

如果我尝试执行以下操作:things=5print("Youhave"+things+"things.")我在Python3.x中收到以下错误:Traceback(mostrecentcalllast):File"",line1,inTypeError:canonlyconcatenatestr(not"int")tostr...和Python2.x中的类似错误:Traceback(mostrecentcalllast):File"",line1,inTypeError:cannotconcatenate'str'and'int'objects我该如何解决这个问题?

python - 将字典的键和值从 `unicode` 转换为 `str` 的最快方法?

我从一个代码“层”接收到一个字典,在将其传递到另一个“层”之前,会在该代码上执行一些计算/修改。原始字典的键和“字符串”值是unicode,但它们被传递到的层只接受str。这将被经常调用,所以我想知道转换以下内容的最快方法是什么:{u'spam':u'eggs',u'foo':True,u'bar':{u'baz':97}}...到:{'spam':'eggs','foo':True,'bar':{'baz':97}}...记住非“字符串”值需要保持其原始类型。有什么想法吗? 最佳答案 DATA={u'spam':u'eggs',u

python - 使用 str.contains 忽略 NaN

我想查找包含字符串的行,如下所示:DF[DF.col.str.contains("foo")]但是,这会失败,因为某些元素是NaN:ValueError:cannotindexwithvectorcontainingNA/NaNvalues所以我求助于混淆DF[DF.col.notnull()][DF.col.dropna().str.contains("foo")]有没有更好的办法? 最佳答案 有一个标志:In[11]:df=pd.DataFrame([["foo1"],["foo2"],["bar"],[np.nan]],col

Python:base64解码时忽略 'Incorrect padding'错误

我有一些经过base64编码的数据,即使其中存在填充错误,我也想将其转换回二进制。如果我使用base64.decodestring(b64_string)它会引发“不正确的填充”错误。还有其他方法吗?更新:感谢所有反馈。老实说,所有提到的方法听起来都有点打击错过了所以我决定尝试openssl。以下命令很有效:opensslenc-d-base64-inb64string-outbinary_data 最佳答案 看来您只需要在解码之前为字节添加填充即可。关于这个问题还有很多其他答案,但我想指出(至少在Python3.x中)base64

python - python中的str性能

在分析一段python代码(python2.6到3.2)时,我发现str方法将对象(在我的例子中是整数)转换为字符串几乎比使用字符串格式化慢一个数量级。这是基准>>>fromtimeitimportTimer>>>Timer('str(100000)').timeit()0.3145311339386332>>>Timer('"%s"%100000').timeit()0.03803517023435887有人知道为什么会这样吗?我错过了什么吗? 最佳答案 '%s'%100000由编译器计算,在运行时等效于常量。>>>importd