共享个人整理的Python问题,有源码,分析过程,解决方案,还有时间戳做间隔

2018.10




#2018-10-23 15:48:47 October Tuesday the 43 week, the 296 day SZ
报错
  File "/Users/apple/Documents/ST/python/Python_test.py", line 4
    Out[5]:
          ^
SyntaxError: invalid syntax

源码:

from collections import defaultdict
dic = defaultdict(list)
dic['first']=1
Out[5]:
defaultdict(list, {'first': 1})
解决方案:

百度后,发现了如下一段代码。发现其实他们很多代码都是这样,

In [4]: li=[1,1.0,True,'hello',1+4j,[1,2,"hello"]]

In [5]: li[0]

Out[5]: 1

In [6]: li[-1]

Out[6]: [1, 2, 'hello']

结论:
这种代码写法:In[4]是输入,Out[5]是代表输出
他们排版有问题,导致他们的代码无法直接运行。想要运行上述代码,只需要删除
Out[5]:
defaultdict(list, {'first': 1})

修改为:

from collections import defaultdict
dic = defaultdict(list)
dic['first']=1
dic['two'] = 2
print(dic)

运行得到:
defaultdict(<class 'list'>, {'first': 1, 'two': 2})
[Finished in 0.0s]

#2018-10-23 13:35:16 October Tuesday the 43 week, the 296 day SZ
Python2和Python3的区别
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(x)?

源代码:
print x 
修改:
print(x)

#2018-10-23 13:33:48 October Tuesday the 43 week, the 296 day SZ
NameError: name 'collections' is not defined
源代码:

queue = collections.deque([(source.x, source.y)])
修改:
from collections import deque
queue = deque([(source.x, source.y)])



#2018-10-23 13:28:07 October Tuesday the 43 week, the 296 day SZ
ModuleNotFoundError: No module named 'Queue'
源代码:        
import Queue
q = Queue.Queue(maxsize = n * m)

修改:
from queue import Queue 

q = Queue(maxsize = n * m)


#2018-10-23 13:26:23 October Tuesday the 43 week, the 296 day SZ

NameError: name 'xrange' is not defined

AttributeError: module 'sys' has no attribute 'maxint'
源代码:
        record = [[sys.maxint for _ in xrange(m)] for i in xrange(n)]
修改:

        record = [[sys.maxsize for _ in range(m)] for i in xrange(n)]
 

看了官网文档后了解python3中没有maxint了,只有maxsize

import sys

i = sys.maxsize

print(i)

 

官网说明文档:https://docs.python.org/3.1/whatsnew/3.0.html#integers



#2018-10-16 09:48:26 October Tuesday the 42 week, the 289 day SZ
            m2 = right - (right - m1) / 2
报错 

TypeError: list indices must be integers or slices, not float
解决方案:
            m2 = right - (right - m1) // 2


#2018-09-20 18:39:47 September Thursday the 38 week, the 263 day SZ
代码:
from sklearn.decomposition import PCA
import numpy as np 
import matplotlib.pyplot as plt 
import scipy.io

data = scipy.io.loadmat('docia.mat') # docia.mat其实是128个640*640的矩阵的叠加,当只有一个通道的时候就是黑白图片,3个通道是RGB图片,128个通道就是128个图片的叠加

#X = data['embedmap'][:,:,127]  #X里面是640个二维数组,每个数组里面有640个元素。也就是一个640*640的矩阵啦。
reshaped_data = data['embedmap'].reshape((409600, 128))   #reshape()是数组对象中的方法,用于改变数组的形状。
#print(X.shape)
#print(len(X))
#print(len(X[0]))
#Y = data['embedmap'][:,:]
pca = PCA(n_components=3) #n_components返回所保留的成分个数n。
pca.fit(reshaped_data)  #fit(X),表示用数据X来训练PCA模型;fit()可以说是scikit-learn中通用的方法,每个需要训练的算法都会有fit()方法,它其实就是算法中的“训练”这一步骤。因为PCA是无监督学习算法,此处y自然等于None。
PCA(copy=True, n_components=3, whiten=True) #whiten=True使得每个特征具有相同的方差。copy=True表示在运行算法时,将原始训练数据复制一份


pcaData=pca.fit_transform(reshaped_data)  #用X来训练PCA模型,同时返回降维后的数据。
res_pcaData = pcaData.reshape((640,640,3))
print(res_pcaData.shape)
print(res_pcaData)
plt.imshow(res_pcaData)
问题: 
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
分析:
我想画图展示三维数组,但是发现三维数组里面的数据是从-9到5的浮点数。这个imshwo函数只能展示0-255的数据


#2018-09-20 12:33:56 September Thursday the 38 week, the 263 day SZ
ValueError: Expected 2D array, got 1D array instead:
array=[-1. -1. -2.  1.  1.  2.].
#2018-09-20 11:36:31 September Thursday the 38 week, the 263 day SZ
代码:
from sklearn.decomposition import PCA
from sklearn.decomposition import PCA, IncrementalPCA
import numpy as np 
import scipy.io

data = scipy.io.loadmat('docia.mat') # 

X = data['embedmap'][:,:,127]
Y = data['embedmap'][:,:]
pca = PCA(n_components=3)
pca.fit(X)
PCA(copy=True, n_components=3, whiten=True)
dim_3 = pca.explained_variance_ratio_
print(dim_3) 
docia_3 = np.append(Y, dim_3,axis = 0)

报错
ValueError: all the input arrays must have same number of dimensions
分析: 
我想把降维后的3维度和以前的数组合并起来。
解决方案: 
方法错了,路线错了,放弃这种合并数组的方法,问题就是数组不匹配



#2018-09-20 10:41:58 September Thursday the 38 week, the 263 day SZ
代码:给128维度降维
import numpy as np 
import scipy.io

data = scipy.io.loadmat('docia.mat') # 

X = data['embedmap'][:,:127]


pca = PCA(n_components=3)
pca.fit(X)
报错
ValueError: Found array with dim 3. Estimator expected <= 2.

分析:PCA只能给2维度数组降维,
解决方案:
X = data['embedmap'][:,:127]
修改为:X = data['embedmap'][:,:,127]
添加逗号才是表示取其中的第三维的全部特征

#2018-09-11 11:04:45 September Tuesday the 37 week, the 254 day SZ
Could not install packages due to an EnvironmentError: [WinError 5] 拒绝访问。: 'c:\\users\\guang\\appdata\\local\\programs\\python\\python35\\Lib\\site-packages\\tensorflow\\python\\_pywrap_tensorflow_internal.pyd'
Consider using the `--user` option or check the permissions.

因为有其他Python进程在使用Python,所以关闭它,我这里是因为跑了在线版的jupyter notbook,关闭它,搞定了


#2018-09-11 10:46:36 September Tuesday the 37 week, the 254 day SZ
'CUDA_VISIBLE_DEVICES' 不是内部或外部命令,也不是可运行的程序 或批处理文件。

#2018-09-06 08:40:20 September Thursday the 36 week, the 249 day SZ
  File "G:\ST\Python\code.py", line 52
    while left < right and (nums[left] == nums[left+1]):
                                                       ^
TabError: inconsistent use of tabs and spaces in indentation
嗯,代码删除,重新全部手写就可以了。

#2018-09-05 09:32:18 September Wednesday the 36 week, the 248 day SZ

    elif add < 0:
                ^
TabError: inconsistent use of tabs and spaces in indentation


#2018-08-30 16:14:11 August Thursday the 35 week, the 242 day SZ
代码:
plt.figure(1)  
问题 
AttributeError: module 'matplotlib' has no attribute 'figure'
解决方案:
import matplotlib as plt
修改为:import matplotlib.pyplot as plt

#2018-08-29 14:06:44 August Wednesday the 35 week, the 241 day SZ
控制栏里运行:
E:\ST\Python\Python_program\SSS\SIGGRAPH18SSS-master>CUDA_VISIBLE_DEVICES=0 ./cuda_executable python main_hyper.py --data-dir ./samples
'CUDA_VISIBLE_DEVICES' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

如何使用指定的CUDA?
cuda设置指定的GPU可见https://blog.csdn.net/u010454261/article/details/70236988 


#2018-08-23 17:39:31 August Thursday the 34 week, the 235 day SZ
ImportError: No module named '_pywrap_tensorflow_internal'

#2018-08-23 17:39:40 August Thursday the 34 week, the 235 day SZ
import tensorflow as tf

OSError: [WinError 126] 找不到指定的模块。
https://blog.csdn.net/wobeatit/article/details/79207196

ImportError: Could not find 'msvcp140.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. 
You may install this DLL by downloading Visual C++ 2015 Redistributable Update 3 from this URL: https://www.microsoft.com/en-us/download/details.aspx?id=53587
解决方案:
ImportError: Could not find 'msvcp140.dll'
这个问题按照提示去官网https://www.microsoft.com/en-us/download/details.aspx?id=53587下载Microsoft Visual C++ 2015 Redistributable Update 3搞定了

#2018-08-23 20:50:47 August Thursday the 34 week, the 235 day SZ
ImportError: Could not find 'cudart64_90.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. 
Download and install CUDA 9.0 from this URL: https://developer.nvidia.com/cuda-90-download-archive
按照网址下载对应的CUDA版本,卸载以前的CUDA版本,安装,重启电脑,成功运行了


#2018-07-18 505319 July Wednesday the 29 week, the 199 day SZ

韩国人:
2018-07-18 19:50:16.857111: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
<bound method Tensor.get_shape of <tf.Tensor 'Reshape:0' shape=(?, 256, 256, 40, 1) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Relu:0' shape=(?, 256, 256, 40, 32) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'MaxPool3D:0' shape=(?, 64, 64, 10, 32) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Relu_1:0' shape=(?, 64, 64, 10, 64) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'MaxPool3D_1:0' shape=(?, 16, 16, 3, 64) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Reshape_1:0' shape=(?, 49152) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Relu_2:0' shape=(?, 1024) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'dropout/mul:0' shape=(?, 1024) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'add_3:0' shape=(?, 4) dtype=float32>>
Traceback (most recent call last):
  File "D:\ST\Python_work\program\CNN-3D-images-Tensorflow-master\simpleCNN_MRI.py", line 102, in <module>
    batch = get_data_MRI(sess,'train',20)
NameError: name 'get_data_MRI' is not defined





#2018-06-12  June Tuesday the 24 week, the 163 day SZ

不知道为啥运行不行了
import tensorflow as tf 
a = tf.constant(1, name = 'a')
b = tf.constant(2, name = 'b')
result = a + b 
sess = tf.Session()
sess.run(result)

2018-06-12 17:46:46.606655: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
[Finished in 7.8s]


#2018-06-11  June Monday the 24 week, the 162 day SZ
TabError: inconsistent use of tabs and spaces in indentation
TabError:缩进中不一致地使用制表符和空格


#2018-06-09  June Saturday the 23 week, the 160 day SZ
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
       
        if prices is None or len(prices) ==0:
          return 0
        begin_value = prices[0]
        result = 0
        for i in prices:
          result = max(result, i - begin_value)
          begin_value = min(begin_value, i)
        return result


prices = [7,1,5,3,6,4]
a = Solution.maxProfit(prices)
print(a)




输出Traceback (most recent call last):
  File "D:\ST\Python_work\test.py", line 20, in <module>
    a = Solution.maxProfit(prices)
TypeError: maxProfit() missing 1 required positional argument: 'prices'
[Finished in 0.5s]

主要是因为,类需要先赋值给一个对象才能使用。
修改:
my_solution = Solution()
prices = [7,1,5,3,6,4]
a = my_solution.maxProfit(prices)
print(a)


#2018-06-06  June Wednesday the 23 week, the 157 day SZ
        dummy = ListNode(0) #初始节点 报错 NameError: name 'ListNode' is not defined

#2018-06-06  June Wednesday the 23 week, the 157 day SZ
            head=head.next     #AttributeError: 'list' object has no attribute 'next'

#2018-05-07 19:47:19 May Monday the 19 week, the 127 day SZ SSMR
本文件放置Python中间遇到的所有问题,标注’问题‘的说明还没有解决
#2018-05-09 14:40:28 May Wednesday the 19 week, the 129 day SZ SSMR
时间复杂度问题:O(n)复杂度小于O(nlogn)吗?但是log没有底数,怎么比较复杂度




#2018-05-31  May Thursday the 22 week, the 151 day SZ
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        len_nums = len(nums)
        for i in range(len_nums):
            for j in range(i +1, len_nums):
                if nums(j)  == target - nums(i):
                    return i, j
                    #break
                else:
                    continue


                    
#2018-05-25  May Friday the 21 week, the 145 day SZ

问题 


class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        temp = 0
        for i in nums:
          temp = temp ^ i 
   
    return temp


my_solution = Solution()

nums = [4,1,2,1,2]
a = my_solution.singleNumber(nums) 
print(a)


  File "D:\ST\Python_work\test.py", line 15
    return temp
              ^
TabError: inconsistent use of tabs and spaces in indentation
TabError:在缩进中不一致地使用制表符和空格。
[Finished in 0.5s]

解决方案:
这个报错就是混用了tab和4个空格造成的,检查代码,要不全部用tab,要不全部用4个空格,或者用idle编辑器校正
我把上述代码重新写了一遍就好了


#2018-05-25  May Friday the 21 week, the 145 day SZ


#只能交易一次股票求最大利润的代码
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
       
        if prices is None or len(prices) ==0:
          return 0
        begin_value = prices[0]  #保留最小的数组值
        result = 0
        for i in prices:
          result = max(result, i - begin_value)
          begin_value = min(begin_value, i)
        return result
prices = [7,1,5,3,6,4]
a = Solution.maxProfit(prices)
print(a)

输出Traceback (most recent call last):
  File "D:\ST\Python_work\test.py", line 20, in <module>
    a = Solution.maxProfit(prices)
TypeError: maxProfit() missing 1 required positional argument: 'prices'
[Finished in 0.5s]

解决方案:
my_solution = Solution()

nums = [4,1,2,1,2]
a = my_solution.singleNumber(nums) 
print(a)

#2018-03-28 09:48:14 March Wednesday the 13 week, the 087 day SZ SSMR
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>

源代码:
filename = 'xingqiudazhan.txt'
# 打开本体TXT文件
text = open(filename).read()
修改后的代码:
text = open(filename, encoding="utf8").read()
需要指定编码方式。
#2018-03-23 19:06:27 March Friday the 12 week, the 082 day SZ SSMR
data = pd.read_csv("room32.csv",index_col='year') #index_col用作行索引的列名 
ValueError: Index year invalid

#2018-03-22 17:43:05 March Thursday the 12 week, the 081 day SZ SSMR
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'235.8333'
http://blog.csdn.net/eastmount/article/details/53144633
235.8333  324.0343  478.3231
236.2708  325.6379  515.4564
238.0521  328.0897  517.0909
235.9063    514.89
236.7604  268.8324  
  404.048 486.0912
237.4167  391.2652  516.233
238.6563  380.8241  
237.6042  388.023 435.3508
238.0313  206.4349  487.675
235.0729    
235.5313  400.0787  660.2347
  411.2069  621.2346
234.4688  395.2343  611.3408
235.5 344.8221  643.0863
235.6354  385.6432  642.3482
234.5521  401.6234  
236 409.6489  602.9347
235.2396  416.8795  589.3457
235.4896    556.3452
236.9688    538.347
我把这个电力数据放进文档里面,并且重命名为missing_data.xls。
import pandas as pd
data = pd.read_excel("missing_data.xls", header=None) 
mm = data.sum()
print (u'计算用电量总数:')
print (mm)这个就出现问题了,百思不得其解,后来百度后,网友说内容有问题,看着用notpad可以打开,但是用Excel但不开,
我后来新建立一个空Excel,把数据放进去,修改整齐,重新运行代码就好了



#2018-02-11 20:19:14 February Sunday the 06 week, the 042 day SZ SSMR
open(test.py,'a').write('99.')

问题如下:名字无法识别,我写了上百行代码都没事,这次就出问题了
Traceback (most recent call last):
  File "D:\Sublime_work_D\Python_work\dafeng.py", line 1, in <module>
    open(test.py,'a').write('99.')
NameError: name 'test' is not defined
[Finished in 0.8s]

修改open('test.py', 'a').write('99')


#2018-02-09 13:48:17 February Friday the 06 week, the 040 day SZ SSMR
D:\\ST\\Python_work\\program\\bridge\\db_export_20180206\\db_export_20180206\\
路径问题
Traceback (most recent call last):
  File "D:\ST\Python_work\program\bridge\db_export_20160325\db_export_20160325\xml2csv.py", line 26, in <module>
    tree = ET.parse(file_in)
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\xml\etree\ElementTree.py", line 1195, in parse
    tree.parse(source, parser)
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\xml\etree\ElementTree.py", line 585, in parse
    source = open(source, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'achineinfos.xml'
用这个文件抽取信息,打算把一个文件夹里面所有的xml文件都提取为CSV文件,但是
machineinfos.xml 出了问题,明明是machineinfos,系统报错为achineinfos.xml,把m吃掉了
修改方法:
把出故障的这行tree = ET.parse(file_in)添加了出错机制,如果出错,报错并且继续处理下面的文件
try:
    tree = ET.parse(file_in):
except FileNotFoundError:
    print("there is no any xml file in this folder")
得到了语法错误:
  File "D:\ST\Python_work\program\bridge\db_export_20160325\db_export_20160325\xml2csv.py", line 27
    tree = ET.parse(file_in):
                            ^
SyntaxError: invalid syntax

后来看了其他的例子,发现是tree后面不用冒号的,删除冒号,进展顺利,发现325文件里面有四个文件有问题,程序无法识别
我要找出有问题的程序
#2018-02-09 10:12:55 February Friday the 06 week, the 040 day SZ SSMR

None,false,None,true,false,Siemens,SSME,Table,T-SN2001,Artis One,None,None,None,2016-03-08T06:44:21.617,None,None,None,None,false,50,false,None,Unknown,false,
最后没有refid的数据,怎样表示这个数据不存在
if refid == ''
or if refid ==' '
or if refid == None
or if refid == 'None'
#2018-02-08 09:31:52 February Thursday the 06 week, the 039 day SZ SSMR


import csv
filename = 'D:\ST\Python_work\output_test1.xml'

reader = csv.reader(open(filename,'rb',encoding="utf-8"))
for index, rows in enumerate(reader):
  if index == 3:
    row = rows
print(row)

Traceback (most recent call last):
  File "<encoding error>", line 5, in <module>
ValueError: binary mode doesn't take an encoding argument
[Finished in 0.7s]

修改:
import csv
filename = 'D:\ST\Python_work\A.csv'
reader = csv.reader(open(filename,'r'))
for index, rows in enumerate(reader):
  #if index == 3: #打印第三行
    #print(index, rows)
  print(rows[1])  #打印第2列
  print(index, rows)  #打印所有行,并且带上索引



#2018-02-08 09:10:45 February Thursday the 06 week, the 039 day SZ SSMR
import csv
filename = 'D:\ST\Python_work\output_test1.xml'

reader = csv.reader(open(filename,'rb'))
for index, rows in enumerate(reader):
  if index == 3:
    row = rows
print(row)


Traceback (most recent call last):
  File "<encoding error>", line 5, in <module>
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
[Finished in 0.7s]

修改:去掉open()函数里面的b就行

import csv
filename = 'D:\ST\Python_work\A.csv'
reader = csv.reader(open(filename,'r'))
for index, rows in enumerate(reader):
  #if index == 3: #打印第三行
    #print(index, rows)
  print(rows[1])  #打印第2列
  print(index, rows)  #打印所有行,并且带上索引


#2018-02-07 16:11:43 February Wednesday the 06 week, the 038 day SZ SSMR
TypeError: write() argument must be str, not list
只能把字符串写入文档,不能把列表写入文档。

#2018-02-07 15:42:33 February Wednesday the 06 week, the 038 day SZ SSMR
for child in root.iter(tag = 'property'):
    value = child.text
    name = child.attrib['name']
    if name != 'testRawData' and name != 'stiffnessRawData' and name != 'stressSeriesRawData' and name != 'stressFullRangeSeriesRawData' and name != 'velocitySeriesRawData' and name != 'velocityFullRangeSeriesRawData' and name != 'machineInfo' and name != 'modificationTime' and name != 'isCacheValid':
        #print(value)
        count2 = count2 +1
        #if count%37 == 0:
         #   print('\n')
        if value == '':
            value = '/'
        str2 = str2 + value + ',' 
        if count2%37 == 0:
            str2 = str2 + '\n'
其中一个i == None 
所以报错
TypeError: Can't convert 'NoneType' object to str implicitly
修改:
if value == None:
    value = 'None'
str2 = str2 + value + ',' 


#2018-02-07 15:20:24 February Wednesday the 06 week, the 038 day SZ SSMR
搞XML2CSV格式时候的问题
SyntaxError: EOF while scanning triple-quoted string literal
#2018-01-31 15:05:18 January Wednesday the 05 week, the 031 day SZ SSMR
Traceback (most recent call last):
  File "<encoding error>", line 16, in <module>
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>
[Finished in 5.6s with exit code 1]

Traceback (most recent call last):
  File "<encoding error>", line 16, in <module>
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>
[Finished in 4.2s with exit code 1]

#2018-01-30 20:03:24 January Tuesday the 05 week, the 030 day SZ SSMR
Traceback (most recent call last):
  File "D:\ST\Python_work\123.py", line 6, in <module>
    text =open("xingqiudazhan.txt").read()
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>
无法打开汉语文件,说编码错误
我把文字放进text里面,依旧说不行啊。


  File "D:\ST\Python_work\123.py", line 7
SyntaxError: Non-UTF-8 code starting with '\xe5' in file D:\ST\Python_work\123.py on line 7, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
[Finished in 0.7s]
长汉字就无法通过
#text = "傻逼了吧爷会爬树凯撒原本向往和平所以又叫猿和平隐居大猴儿峦后来在上校的逼迫下猿力觉醒成为大总统猿世凯发动猩球大战最后打败人类自称猿始皇年号大猿国歌猩条旗永不落续集可以讲他焚书坑猴铸十二金猴发明吮指猿味鸡成立坏猴子影业写金刚经按照这个思路还可以再拍七八十集回看这个系列真的从始至终都表达了自己要说的东西作为暑期大片实为难得这部终章直指美国是建立在奴隶制的基础上猿族劳役时竟大放星条旗永不落真是太讽刺反派就像纳粹种族清洗者和现代启示录的白兰度的结合纳粹思维的荒谬和疯狂令人瞠目瑟金斯真的值一个奥斯卡提名这绝对是这个系列最得当的收官首先这是一部非常成熟的商业片从场景特效到人物故事每一样都相辅相成得刚刚好而凯撒的成长更是这个系列的妙义所在从第一部的自我建立到第二部的自我认知再到这一部的自我升华凯撒带领一众徒子徒孙完成了一场人类也无法企及的精神建设壮阔的猿族史诗当猿进化得越来越像人而人越来越堕落疯狂观众只能义无反顾的站到自身的对立面在灵长类动物身上寻找久违的人性导演反人类反得不寒而栗啊这是有多大仇自从看了变形金刚我接受能力强了许多也宽容了许多微笑结尾人类死光光猿类伤亡惨重然而猿猴头子们骑的那几匹马经历了肉搏逃亡爆炸雪崩后仍毫发无伤那个特搞笑的猴子是哈利波特里家养小精灵多比的远亲嘛再次感叹烂不可怕最可怕的是平庸三部曲这么乏味地结束还蛮遗憾的越玩越深了寓言故事一则透过人与猩猩去反思人类自己的社会结构可以做很深的解读以及感谢如此出色的视觉技术才可以让故事可信度更高以及真是最后一部了接下来该马崛起了吧咋改朝换代了还只有被骑的份啊烂炸天警报警报警报好莱坞暑期档头号影骗来袭看完之后的感觉就是上当了受骗了这特么根本算不上一部前传三部曲的最终章也根本没有什么终极之战而是剧情乏味逻辑荒谬场面缩水结局糊弄的失败之作如果你带着对前两部的好印象去观影的话收获的就是大失望猩猩最初的居住地莫不是花果山孙悟空烂到换个主题就是一出建党伟业都哪跟哪儿啊桥段强行拼凑一起跟百度大脑编得剧似的军营重犯牢房任由小屁孩进出雪山中一箭不包扎走到温带才死对方导弹满天飞造石墙挡编剧想到哪写哪而且居然还毫无爆点神了情感的张力称得上饱满剧情节奏稍慢很容易被凯撒的情绪起伏感染得热泪盈眶最后真是一个反人类的五星结局拍猩猩都能熬成美式老鸡汤美国人都看不下去纷纷离场反科学没逻辑的狗血故事比手撕鬼子还没有想象力一群可以适应任何气候的猩猩徒手战斗力跟人持平骑马马招谁惹谁了被人类虐待的程度还不如山西黑煤窑首领中箭坚持爬雪山过草地长征完箭伤还在流血终于失血过多而亡又名猩球崛起掘地逃亡没有终极一战只有人类终极作死懂爬树才是生存之本前作玩张力本作玩寓言几处讽刺精彩但是把人类智商强搞下线一群有如神助的猩猩把人类赶下台真不够说服力另外导演沉稳细腻大气风玩过头了前半段节奏超慢三部曲对比给安迪瑟金斯加星凱薩全程智商下線这几年在影院看过的最糟略去科幻作为一动作片都是文戏开头总共加起来分钟不到的武戏后进入长达小时多分钟的地狱式文戏文戏也没什么全是陈谷子烂麻子内容一条臭裹脚布楞是抻得没完没了磨磨唧唧惨不忍睹星吧之前第二部精彩就在于凯撒和科巴正反两派的角色都交相辉映而第三部里作为大反派的人类上校的角色始终立不住太虚太平庸动机太弱凯撒又高大全动机也弱电影张力一下子弱了好多全片也就差强人意了质量其实还是很赞的但始终差口气"

text = "我来到北京清华大学"
seg_list = jieba.cut(text,cut_all = True, HMM = False)

print("full mode:" + "/".join(seg_list))
full mode:我/来到/北京/清华/清华大学/华大/大学
[Finished in 5.5s]


#2018-01-30 16:51:54 January Tuesday the 05 week, the 030 day SZ SSMR
siglist = [1,2, 3]
text = " ".join(siglist)
print('text')
Traceback (most recent call last):
  File "D:\ST\Python_work\Python_Test.py", line 2, in <module>
    text = " ".join(siglist)
TypeError: sequence item 0: expected str instance, int found
[Finished in 1.2s]
修改,列表里面的东西为字符
siglist = ['1', '2', '3']
text = "".join(siglist)
print(text)





#2018-01-28 19:01:10 January Sunday the 04 week, the 028 day SZ SSMR

from wxpy import *
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot("deepThought")# 用于回复消息的机器人
chatbot.set_trainer(ChatterBotCorpusTrainer)
chatbot.train("chatterbot.corpus.chinese")# 使用该库的中文语料库
bot = Bot(cache_path=True)# 用于接入微信的机器人

group_2 = bot.groups("友谊是")[0]# 进行测试的群
group_2.send("hi")

@bot.register(group_2)

def reply_my_friend(msg):
   print(msg)
   return chatbot.get_response(msg.text).text# 使用机器人进行自动回复

# 堵塞线程,并进入 Python 命令行
embed()




xml.parsers.expat.ExpatError: no element found: line 1, column 0
[Finished in 21.3s with exit code 1]
这个问题删除了昨天生成的两个文件就没有了
参考下面
#2018-01-27 15:01:51 January Saturday the 04 week, the 027 day SZ SSMR
这行没有问题,可以生成一个二维码图片让扫描登陆,然后看到微信最顶部说已经登陆了网页版微信,其实,我自己并没有登陆。
并且在下面记录聊天记录,但是只能和一个特定的群聊天
搞定了,里面有个group2这个东西,这个东西说明了只和某个群聊天。
因为@bot.register(group_2)
这个代码很神奇,他怎么知道是让我的微信登陆网页版,而不是其他人的微信登陆网页版。因为代码里面并没有提到我的微信相关信息
#2018-01-28 19:30:39 January Sunday the 04 week, the 028 day SZ SSMR
今天再次运行此代码,直接让我在微信上登陆网页版,没有了二维码登陆,很是奇怪。
后来用控制栏运行了,发现在该文件的文件夹里会产生两个文件,一个就是需要登陆的二维码文件,另外一个是db.sqlite3
因为文件夹里的二维码文件一直没有删除,所有程序会自动认出这段代码是我的账号。以后就不用删除那个登陆二维码,这样手机直接点击登陆就行。
删除两个文件重新运行,重新生成登陆二维码,扫描后竟然报错
KeyError: 'pass_ticket'
网友说是这个给定的键是有一天的有效期,过了一天就完了


#2018-01-28 18:37:44 January Sunday the 04 week, the 028 day SZ SSMR
from wxpy import *
bot = Bot(cache_path=True)# 用于接入微信的机器人
这行代码昨天登陆没事,还可以制作聊天机器人,今天登陆就报错


    parser.Parse(string, True)
xml.parsers.expat.ExpatError: no element found: line 1, column 0
#2018-01-28 18:32:24 January Sunday the 04 week, the 028 day SZ SSMR
import itchat
itchat.login()
friends = itchat.get_friends(update = True)[0:]
以上代码生成一个二维码登陆图片,但是登陆时候报错,按照网上指导,不应该报错的。
昨天我弄聊天机器人登陆都没有问题,今天就有问题了,而且今天网页版也无法登陆了。可能是被腾讯屏蔽了
█
Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
Loading the contact, this may take a little while.
Traceback (most recent call last):
  File "D:\ST\Python_work\Python_Test.py", line 2, in <module>
    itchat.login()
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\site-packages\itchat\components\login.py", line 66, in login
    self.show_mobile_login()
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\site-packages\itchat\components\login.py", line 212, in show_mobile_login
    self.loginInfo['url'], self.loginInfo['pass_ticket'])
KeyError: 'pass_ticket'
[Finished in 20.1s]

#2018-01-27 13:49:40 January Saturday the 04 week, the 027 day SZ SSMR
C:\Users\z003tesj>pip install json
Collecting json
  Could not find a version that satisfies the requirement json (from versions: )

No matching distribution found for json
解决微信公众号聊天机器人,需要这个json库,但是无法安装
方案:去如下网站下载了simplejson库,或者直接pip simplejson
https://www.lfd.uci.edu/~gohlke/pythonlibs/#simplejson

#2018-01-27 14:08:28 January Saturday the 04 week, the 027 day SZ SSMR
聊天机器人代码如下

import requests
from wxpy import *
import simplejson


#图灵机器人
def talks_robot(info = '你叫什么名字'):
    api_url = 'http://www.tuling123.com/openapi/api'
    apikey = 'a1bbc12dd78b4837b22cd8e98d96e027'
    data = {'key': apikey,
                'info': info}
    req = requests.post(api_url, data=data).text
    replys = json.loads(req)['text']
    return replys

#微信自动回复
robot = Robot()
# 回复来自其他好友、群聊和公众号的消息
@robot.register()
def reply_my_friend(msg):
    message = '{}'.format(msg.text)
    replys = talks_robot(info=message)
    return replys

# 开始监听和自动处理消息
robot.start()

出现如下问题:
█
Traceback (most recent call last):
  File "D:\ST\Python_work\Python_Test.py", line 18, in <module>
    robot = Robot()
NameError: name 'Robot' is not defined
[Finished in 2.1s]
解决方案:
尝试登陆网页版微信和微信公众号也是没用啊
后来换了其他人的代码就可以了



2018-01-22 19:47:23 January Monday the 04 week, the 022 day
D:\EventlogAnalyzer>python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
运行德国人10000行的py文件时候出现问题,我用的Python2.7.14

D:\EventlogAnalyzer>python eventlogAnalyzer.py
Traceback (most recent call last):
  File "eventlogAnalyzer.py", line 19, in <module>
    import wx, os ,re, time, sys,itertools
ImportError: No module named wx

D:\EventlogAnalyzer>

后来我用手机下载wx,返回如下,可能是我的Python2.7.14版本太高了
D:\EventlogAnalyzer>python eventlogAnalyzer.py
Traceback (most recent call last):
  File "eventlogAnalyzer.py", line 19, in <module>
    import wx, os ,re, time, sys,itertools
ImportError: No module named wx

2017-12-17 18:15:08 December Sunday the 50 week, the 351 day
IndentationError: unexpected indent
[Finished in 0.8s with exit code 1]

缩进错误,检查下哪里有问题。

2017-12-17 16:38:07 December Sunday the 50 week, the 351 day
'''
# -*- coding:utf-8 -*- 
#把从CSDN复制的程序放在test.py这个文件里
filename = 'test.py'
#得到新的没有数字和点的文件
filename_new = 'test_new.py'
#打开旧文件
with open(filename) as file_object:
  #得到文件里所有行
  lines = file_object.readlines()
  循环取出文件里的每行
  for line in lines:
    #删除每行的前三个字符,也就是删除数字和点。
    new_line = line[3:]
    #把删除后的行依次放入新文件里面,如果新文件不存在就自动创建该文件。
    open(filename_new,'a').write(new_line)
'''
open(test.py,'a').write('99.')

问题如下:名字无法识别,我写了上百行代码都没事,这次就出问题了
Traceback (most recent call last):
  File "D:\Sublime_work_D\Python_work\dafeng.py", line 1, in <module>
    open(test.py,'a').write('99.')
NameError: name 'test' is not defined
[Finished in 0.8s]
解决方案:给test.py加上引号就行了,


Traceback (most recent call last):
  File "D:\Sublime_work_D\Python_work\article.py", line 9, in <module>
    lines = file_object.readlines()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 21: illegal multibyte sequence
[Finished in 1.0s with exit code 1]

解决办法:删除了复制代码test.py里面的汉字,通过判断#标志,删除对应行就行。

在Python处理字符编码时出现如下错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xb1 in position 0: invalid start byte

此种错误,有几种可能: 
(1)要处理的字符串本身不是gbk编码,但是你却以gbk编码去解码 
比如,字符串本身是utf-8的,但是你却用gbk去解码utf-8的字符串,所以结果不用说,则必然出错

则必然会出现这类的错误,说是,用gbk的方式去解码字符串,想要获得Unicode字符串,但是结果却解码出错了

解决办法:

如果你确定当前字符串,比如抓取网页通过charset=utf-8,已经确定html的字符串是utf-8的,

则可以直接去通过utf-8去解码。


具体业务场景如下:

我读入一个编码为GBK的文件,解析里面的汉字,使用utf-8编码进行正则匹配,出现上述问题

解决方法:

设置python编码为GBK
 #encoding=utf8
 import sys
 reload(sys)
 sys.setdefaultencoding('gbk') 


python xml处理中文时出现的错误,记录一下,以免忘记

 

"UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)"

解决办法,在该python文件的前面加上如下几句,问题得到解决。

import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)




2017-12-17 16:38:04 December Sunday the 50 week, the 351 day
1.py文件总是经常有这个问题,could not convert string to float: 'vertex'
查证后发现linedatas中竟然还有vertex这个字符串存在,也就是strip('vertex ')没有起到应有的作用。
  line_datas = line.strip('vertex ')#.strip().split()

  File "D:\Sublime_work\Python_work\stl2xml_simple.py", line 62, in get_body_xml
    data =float(line_data)/1000       #divie 1000 for each number in vertex line
ValueError: could not convert string to float: 'vertex'
[Finished in 0.9s with exit code 1]
方案:最后换了其他的删除字符方式解决了问题
2017-12-17 16:37:59 December Sunday the 50 week, the 351 day
2
from .models import Topic
#2017-08-01 17:34:06
from .forms import TopicForm

    from .forms import TopicForm
ModuleNotFoundError: No module named 'learning_logs.forms'

    from .forms import TopicForm
ModuleNotFoundError: No module named '__main__.forms'; '__main__' is not a package
[Finished in 1.3s with exit code 1]

    from .models import Topic
SystemError: Parent module '' not loaded, cannot perform relative import

    from django.forms import TopicForm
ImportError: cannot import name 'TopicForm'






#2018-10-05 18:38:45 October Friday the 40 week, the 278 day SZ
def power(x, n):
    if n == 0:
        return 1
    if n % 2 == 0:
        temp = power(x, n//2)
        return temp * temp
    else:
        temp = power(x, n/2)
        return temp * temp * x

p = power(2, 3)
print(p)
报错:
RecursionError: maximum recursion depth exceeded in comparison
解决方案:
        temp = power(x, n//2)



#2018-10-03 20:43:09 October Wednesday the 40 week, the 276 day SZ
#from math import log
n = 10
sum = 0
for i in [1<<i for i in range(int(log(n,2)))]:
    sum += 1
print(sum)
问题: 
NameError: name 'log' is not defined
解决方案:
添加:
from math import log




#2018-07-18 505319 July Wednesday the 29 week, the 199 day SZ

韩国人:
2018-07-18 19:50:16.857111: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
<bound method Tensor.get_shape of <tf.Tensor 'Reshape:0' shape=(?, 256, 256, 40, 1) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Relu:0' shape=(?, 256, 256, 40, 32) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'MaxPool3D:0' shape=(?, 64, 64, 10, 32) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Relu_1:0' shape=(?, 64, 64, 10, 64) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'MaxPool3D_1:0' shape=(?, 16, 16, 3, 64) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Reshape_1:0' shape=(?, 49152) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'Relu_2:0' shape=(?, 1024) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'dropout/mul:0' shape=(?, 1024) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'add_3:0' shape=(?, 4) dtype=float32>>
Traceback (most recent call last):
  File "D:\ST\Python_work\program\CNN-3D-images-Tensorflow-master\simpleCNN_MRI.py", line 102, in <module>
    batch = get_data_MRI(sess,'train',20)
NameError: name 'get_data_MRI' is not defined





#2018-06-12  June Tuesday the 24 week, the 163 day SZ

不知道为啥运行不行了
import tensorflow as tf 
a = tf.constant(1, name = 'a')
b = tf.constant(2, name = 'b')
result = a + b 
sess = tf.Session()
sess.run(result)

2018-06-12 17:46:46.606655: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
[Finished in 7.8s]


#2018-06-11  June Monday the 24 week, the 162 day SZ
TabError: inconsistent use of tabs and spaces in indentation
TabError:缩进中不一致地使用制表符和空格


#2018-06-09  June Saturday the 23 week, the 160 day SZ
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
       
        if prices is None or len(prices) ==0:
          return 0
        begin_value = prices[0]
        result = 0
        for i in prices:
          result = max(result, i - begin_value)
          begin_value = min(begin_value, i)
        return result


prices = [7,1,5,3,6,4]
a = Solution.maxProfit(prices)
print(a)




输出Traceback (most recent call last):
  File "D:\ST\Python_work\test.py", line 20, in <module>
    a = Solution.maxProfit(prices)
TypeError: maxProfit() missing 1 required positional argument: 'prices'
[Finished in 0.5s]

主要是因为,类需要先赋值给一个对象才能使用。
修改:
my_solution = Solution()
prices = [7,1,5,3,6,4]
a = my_solution.maxProfit(prices)
print(a)


#2018-06-06  June Wednesday the 23 week, the 157 day SZ
        dummy = ListNode(0) #初始节点 报错 NameError: name 'ListNode' is not defined

#2018-06-06  June Wednesday the 23 week, the 157 day SZ
            head=head.next     #AttributeError: 'list' object has no attribute 'next'

#2018-05-07 19:47:19 May Monday the 19 week, the 127 day SZ SSMR
本文件放置Python中间遇到的所有问题,标注’问题‘的说明还没有解决
#2018-05-09 14:40:28 May Wednesday the 19 week, the 129 day SZ SSMR
时间复杂度问题:O(n)复杂度小于O(nlogn)吗?但是log没有底数,怎么比较复杂度




#2018-05-31  May Thursday the 22 week, the 151 day SZ
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        len_nums = len(nums)
        for i in range(len_nums):
            for j in range(i +1, len_nums):
                if nums(j)  == target - nums(i):
                    return i, j
                    #break
                else:
                    continue


                    
#2018-05-25  May Friday the 21 week, the 145 day SZ

问题 


class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        temp = 0
        for i in nums:
          temp = temp ^ i 
   
    return temp


my_solution = Solution()

nums = [4,1,2,1,2]
a = my_solution.singleNumber(nums) 
print(a)


  File "D:\ST\Python_work\test.py", line 15
    return temp
              ^
TabError: inconsistent use of tabs and spaces in indentation
TabError:在缩进中不一致地使用制表符和空格。
[Finished in 0.5s]

解决方案:
这个报错就是混用了tab和4个空格造成的,检查代码,要不全部用tab,要不全部用4个空格,或者用idle编辑器校正
我把上述代码重新写了一遍就好了


#2018-05-25  May Friday the 21 week, the 145 day SZ


#只能交易一次股票求最大利润的代码
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
       
        if prices is None or len(prices) ==0:
          return 0
        begin_value = prices[0]  #保留最小的数组值
        result = 0
        for i in prices:
          result = max(result, i - begin_value)
          begin_value = min(begin_value, i)
        return result
prices = [7,1,5,3,6,4]
a = Solution.maxProfit(prices)
print(a)

输出Traceback (most recent call last):
  File "D:\ST\Python_work\test.py", line 20, in <module>
    a = Solution.maxProfit(prices)
TypeError: maxProfit() missing 1 required positional argument: 'prices'
[Finished in 0.5s]

解决方案:
my_solution = Solution()

nums = [4,1,2,1,2]
a = my_solution.singleNumber(nums) 
print(a)

#2018-03-28 09:48:14 March Wednesday the 13 week, the 087 day SZ SSMR
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>

源代码:
filename = 'xingqiudazhan.txt'
# 打开本体TXT文件
text = open(filename).read()
修改后的代码:
text = open(filename, encoding="utf8").read()
需要指定编码方式。
#2018-03-23 19:06:27 March Friday the 12 week, the 082 day SZ SSMR
data = pd.read_csv("room32.csv",index_col='year') #index_col用作行索引的列名 
ValueError: Index year invalid

#2018-03-22 17:43:05 March Thursday the 12 week, the 081 day SZ SSMR
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'235.8333'
http://blog.csdn.net/eastmount/article/details/53144633
235.8333  324.0343  478.3231
236.2708  325.6379  515.4564
238.0521  328.0897  517.0909
235.9063    514.89
236.7604  268.8324  
  404.048 486.0912
237.4167  391.2652  516.233
238.6563  380.8241  
237.6042  388.023 435.3508
238.0313  206.4349  487.675
235.0729    
235.5313  400.0787  660.2347
  411.2069  621.2346
234.4688  395.2343  611.3408
235.5 344.8221  643.0863
235.6354  385.6432  642.3482
234.5521  401.6234  
236 409.6489  602.9347
235.2396  416.8795  589.3457
235.4896    556.3452
236.9688    538.347
我把这个电力数据放进文档里面,并且重命名为missing_data.xls。
import pandas as pd
data = pd.read_excel("missing_data.xls", header=None) 
mm = data.sum()
print (u'计算用电量总数:')
print (mm)这个就出现问题了,百思不得其解,后来百度后,网友说内容有问题,看着用notpad可以打开,但是用Excel但不开,
我后来新建立一个空Excel,把数据放进去,修改整齐,重新运行代码就好了



#2018-02-11 20:19:14 February Sunday the 06 week, the 042 day SZ SSMR
open(test.py,'a').write('99.')

问题如下:名字无法识别,我写了上百行代码都没事,这次就出问题了
Traceback (most recent call last):
  File "D:\Sublime_work_D\Python_work\dafeng.py", line 1, in <module>
    open(test.py,'a').write('99.')
NameError: name 'test' is not defined
[Finished in 0.8s]

修改open('test.py', 'a').write('99')


#2018-02-09 13:48:17 February Friday the 06 week, the 040 day SZ SSMR
D:\\ST\\Python_work\\program\\bridge\\db_export_20180206\\db_export_20180206\\
路径问题
Traceback (most recent call last):
  File "D:\ST\Python_work\program\bridge\db_export_20160325\db_export_20160325\xml2csv.py", line 26, in <module>
    tree = ET.parse(file_in)
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\xml\etree\ElementTree.py", line 1195, in parse
    tree.parse(source, parser)
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\xml\etree\ElementTree.py", line 585, in parse
    source = open(source, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'achineinfos.xml'
用这个文件抽取信息,打算把一个文件夹里面所有的xml文件都提取为CSV文件,但是
machineinfos.xml 出了问题,明明是machineinfos,系统报错为achineinfos.xml,把m吃掉了
修改方法:
把出故障的这行tree = ET.parse(file_in)添加了出错机制,如果出错,报错并且继续处理下面的文件
try:
    tree = ET.parse(file_in):
except FileNotFoundError:
    print("there is no any xml file in this folder")
得到了语法错误:
  File "D:\ST\Python_work\program\bridge\db_export_20160325\db_export_20160325\xml2csv.py", line 27
    tree = ET.parse(file_in):
                            ^
SyntaxError: invalid syntax

后来看了其他的例子,发现是tree后面不用冒号的,删除冒号,进展顺利,发现325文件里面有四个文件有问题,程序无法识别
我要找出有问题的程序
#2018-02-09 10:12:55 February Friday the 06 week, the 040 day SZ SSMR

None,false,None,true,false,Siemens,SSME,Table,T-SN2001,Artis One,None,None,None,2016-03-08T06:44:21.617,None,None,None,None,false,50,false,None,Unknown,false,
最后没有refid的数据,怎样表示这个数据不存在
if refid == ''
or if refid ==' '
or if refid == None
or if refid == 'None'
#2018-02-08 09:31:52 February Thursday the 06 week, the 039 day SZ SSMR


import csv
filename = 'D:\ST\Python_work\output_test1.xml'

reader = csv.reader(open(filename,'rb',encoding="utf-8"))
for index, rows in enumerate(reader):
  if index == 3:
    row = rows
print(row)

Traceback (most recent call last):
  File "<encoding error>", line 5, in <module>
ValueError: binary mode doesn't take an encoding argument
[Finished in 0.7s]

修改:
import csv
filename = 'D:\ST\Python_work\A.csv'
reader = csv.reader(open(filename,'r'))
for index, rows in enumerate(reader):
  #if index == 3: #打印第三行
    #print(index, rows)
  print(rows[1])  #打印第2列
  print(index, rows)  #打印所有行,并且带上索引



#2018-02-08 09:10:45 February Thursday the 06 week, the 039 day SZ SSMR
import csv
filename = 'D:\ST\Python_work\output_test1.xml'

reader = csv.reader(open(filename,'rb'))
for index, rows in enumerate(reader):
  if index == 3:
    row = rows
print(row)


Traceback (most recent call last):
  File "<encoding error>", line 5, in <module>
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
[Finished in 0.7s]

修改:去掉open()函数里面的b就行

import csv
filename = 'D:\ST\Python_work\A.csv'
reader = csv.reader(open(filename,'r'))
for index, rows in enumerate(reader):
  #if index == 3: #打印第三行
    #print(index, rows)
  print(rows[1])  #打印第2列
  print(index, rows)  #打印所有行,并且带上索引


#2018-02-07 16:11:43 February Wednesday the 06 week, the 038 day SZ SSMR
TypeError: write() argument must be str, not list
只能把字符串写入文档,不能把列表写入文档。

#2018-02-07 15:42:33 February Wednesday the 06 week, the 038 day SZ SSMR
for child in root.iter(tag = 'property'):
    value = child.text
    name = child.attrib['name']
    if name != 'testRawData' and name != 'stiffnessRawData' and name != 'stressSeriesRawData' and name != 'stressFullRangeSeriesRawData' and name != 'velocitySeriesRawData' and name != 'velocityFullRangeSeriesRawData' and name != 'machineInfo' and name != 'modificationTime' and name != 'isCacheValid':
        #print(value)
        count2 = count2 +1
        #if count%37 == 0:
         #   print('\n')
        if value == '':
            value = '/'
        str2 = str2 + value + ',' 
        if count2%37 == 0:
            str2 = str2 + '\n'
其中一个i == None 
所以报错
TypeError: Can't convert 'NoneType' object to str implicitly
修改:
if value == None:
    value = 'None'
str2 = str2 + value + ',' 


#2018-02-07 15:20:24 February Wednesday the 06 week, the 038 day SZ SSMR
搞XML2CSV格式时候的问题
SyntaxError: EOF while scanning triple-quoted string literal
#2018-01-31 15:05:18 January Wednesday the 05 week, the 031 day SZ SSMR
Traceback (most recent call last):
  File "<encoding error>", line 16, in <module>
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>
[Finished in 5.6s with exit code 1]

Traceback (most recent call last):
  File "<encoding error>", line 16, in <module>
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>
[Finished in 4.2s with exit code 1]

#2018-01-30 20:03:24 January Tuesday the 05 week, the 030 day SZ SSMR
Traceback (most recent call last):
  File "D:\ST\Python_work\123.py", line 6, in <module>
    text =open("xingqiudazhan.txt").read()
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>
无法打开汉语文件,说编码错误
我把文字放进text里面,依旧说不行啊。


  File "D:\ST\Python_work\123.py", line 7
SyntaxError: Non-UTF-8 code starting with '\xe5' in file D:\ST\Python_work\123.py on line 7, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
[Finished in 0.7s]
长汉字就无法通过
#text = "傻逼了吧爷会爬树凯撒原本向往和平所以又叫猿和平隐居大猴儿峦后来在上校的逼迫下猿力觉醒成为大总统猿世凯发动猩球大战最后打败人类自称猿始皇年号大猿国歌猩条旗永不落续集可以讲他焚书坑猴铸十二金猴发明吮指猿味鸡成立坏猴子影业写金刚经按照这个思路还可以再拍七八十集回看这个系列真的从始至终都表达了自己要说的东西作为暑期大片实为难得这部终章直指美国是建立在奴隶制的基础上猿族劳役时竟大放星条旗永不落真是太讽刺反派就像纳粹种族清洗者和现代启示录的白兰度的结合纳粹思维的荒谬和疯狂令人瞠目瑟金斯真的值一个奥斯卡提名这绝对是这个系列最得当的收官首先这是一部非常成熟的商业片从场景特效到人物故事每一样都相辅相成得刚刚好而凯撒的成长更是这个系列的妙义所在从第一部的自我建立到第二部的自我认知再到这一部的自我升华凯撒带领一众徒子徒孙完成了一场人类也无法企及的精神建设壮阔的猿族史诗当猿进化得越来越像人而人越来越堕落疯狂观众只能义无反顾的站到自身的对立面在灵长类动物身上寻找久违的人性导演反人类反得不寒而栗啊这是有多大仇自从看了变形金刚我接受能力强了许多也宽容了许多微笑结尾人类死光光猿类伤亡惨重然而猿猴头子们骑的那几匹马经历了肉搏逃亡爆炸雪崩后仍毫发无伤那个特搞笑的猴子是哈利波特里家养小精灵多比的远亲嘛再次感叹烂不可怕最可怕的是平庸三部曲这么乏味地结束还蛮遗憾的越玩越深了寓言故事一则透过人与猩猩去反思人类自己的社会结构可以做很深的解读以及感谢如此出色的视觉技术才可以让故事可信度更高以及真是最后一部了接下来该马崛起了吧咋改朝换代了还只有被骑的份啊烂炸天警报警报警报好莱坞暑期档头号影骗来袭看完之后的感觉就是上当了受骗了这特么根本算不上一部前传三部曲的最终章也根本没有什么终极之战而是剧情乏味逻辑荒谬场面缩水结局糊弄的失败之作如果你带着对前两部的好印象去观影的话收获的就是大失望猩猩最初的居住地莫不是花果山孙悟空烂到换个主题就是一出建党伟业都哪跟哪儿啊桥段强行拼凑一起跟百度大脑编得剧似的军营重犯牢房任由小屁孩进出雪山中一箭不包扎走到温带才死对方导弹满天飞造石墙挡编剧想到哪写哪而且居然还毫无爆点神了情感的张力称得上饱满剧情节奏稍慢很容易被凯撒的情绪起伏感染得热泪盈眶最后真是一个反人类的五星结局拍猩猩都能熬成美式老鸡汤美国人都看不下去纷纷离场反科学没逻辑的狗血故事比手撕鬼子还没有想象力一群可以适应任何气候的猩猩徒手战斗力跟人持平骑马马招谁惹谁了被人类虐待的程度还不如山西黑煤窑首领中箭坚持爬雪山过草地长征完箭伤还在流血终于失血过多而亡又名猩球崛起掘地逃亡没有终极一战只有人类终极作死懂爬树才是生存之本前作玩张力本作玩寓言几处讽刺精彩但是把人类智商强搞下线一群有如神助的猩猩把人类赶下台真不够说服力另外导演沉稳细腻大气风玩过头了前半段节奏超慢三部曲对比给安迪瑟金斯加星凱薩全程智商下線这几年在影院看过的最糟略去科幻作为一动作片都是文戏开头总共加起来分钟不到的武戏后进入长达小时多分钟的地狱式文戏文戏也没什么全是陈谷子烂麻子内容一条臭裹脚布楞是抻得没完没了磨磨唧唧惨不忍睹星吧之前第二部精彩就在于凯撒和科巴正反两派的角色都交相辉映而第三部里作为大反派的人类上校的角色始终立不住太虚太平庸动机太弱凯撒又高大全动机也弱电影张力一下子弱了好多全片也就差强人意了质量其实还是很赞的但始终差口气"

text = "我来到北京清华大学"
seg_list = jieba.cut(text,cut_all = True, HMM = False)

print("full mode:" + "/".join(seg_list))
full mode:我/来到/北京/清华/清华大学/华大/大学
[Finished in 5.5s]


#2018-01-30 16:51:54 January Tuesday the 05 week, the 030 day SZ SSMR
siglist = [1,2, 3]
text = " ".join(siglist)
print('text')
Traceback (most recent call last):
  File "D:\ST\Python_work\Python_Test.py", line 2, in <module>
    text = " ".join(siglist)
TypeError: sequence item 0: expected str instance, int found
[Finished in 1.2s]
修改,列表里面的东西为字符
siglist = ['1', '2', '3']
text = "".join(siglist)
print(text)





#2018-01-28 19:01:10 January Sunday the 04 week, the 028 day SZ SSMR

from wxpy import *
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot("deepThought")# 用于回复消息的机器人
chatbot.set_trainer(ChatterBotCorpusTrainer)
chatbot.train("chatterbot.corpus.chinese")# 使用该库的中文语料库
bot = Bot(cache_path=True)# 用于接入微信的机器人

group_2 = bot.groups("友谊是")[0]# 进行测试的群
group_2.send("hi")

@bot.register(group_2)

def reply_my_friend(msg):
   print(msg)
   return chatbot.get_response(msg.text).text# 使用机器人进行自动回复

# 堵塞线程,并进入 Python 命令行
embed()




xml.parsers.expat.ExpatError: no element found: line 1, column 0
[Finished in 21.3s with exit code 1]
这个问题删除了昨天生成的两个文件就没有了
参考下面
#2018-01-27 15:01:51 January Saturday the 04 week, the 027 day SZ SSMR
这行没有问题,可以生成一个二维码图片让扫描登陆,然后看到微信最顶部说已经登陆了网页版微信,其实,我自己并没有登陆。
并且在下面记录聊天记录,但是只能和一个特定的群聊天
搞定了,里面有个group2这个东西,这个东西说明了只和某个群聊天。
因为@bot.register(group_2)
这个代码很神奇,他怎么知道是让我的微信登陆网页版,而不是其他人的微信登陆网页版。因为代码里面并没有提到我的微信相关信息
#2018-01-28 19:30:39 January Sunday the 04 week, the 028 day SZ SSMR
今天再次运行此代码,直接让我在微信上登陆网页版,没有了二维码登陆,很是奇怪。
后来用控制栏运行了,发现在该文件的文件夹里会产生两个文件,一个就是需要登陆的二维码文件,另外一个是db.sqlite3
因为文件夹里的二维码文件一直没有删除,所有程序会自动认出这段代码是我的账号。以后就不用删除那个登陆二维码,这样手机直接点击登陆就行。
删除两个文件重新运行,重新生成登陆二维码,扫描后竟然报错
KeyError: 'pass_ticket'
网友说是这个给定的键是有一天的有效期,过了一天就完了


#2018-01-28 18:37:44 January Sunday the 04 week, the 028 day SZ SSMR
from wxpy import *
bot = Bot(cache_path=True)# 用于接入微信的机器人
这行代码昨天登陆没事,还可以制作聊天机器人,今天登陆就报错


    parser.Parse(string, True)
xml.parsers.expat.ExpatError: no element found: line 1, column 0
#2018-01-28 18:32:24 January Sunday the 04 week, the 028 day SZ SSMR
import itchat
itchat.login()
friends = itchat.get_friends(update = True)[0:]
以上代码生成一个二维码登陆图片,但是登陆时候报错,按照网上指导,不应该报错的。
昨天我弄聊天机器人登陆都没有问题,今天就有问题了,而且今天网页版也无法登陆了。可能是被腾讯屏蔽了
█
Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
Loading the contact, this may take a little while.
Traceback (most recent call last):
  File "D:\ST\Python_work\Python_Test.py", line 2, in <module>
    itchat.login()
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\site-packages\itchat\components\login.py", line 66, in login
    self.show_mobile_login()
  File "C:\Users\z003tesj\AppData\Local\Programs\Python\Python35\lib\site-packages\itchat\components\login.py", line 212, in show_mobile_login
    self.loginInfo['url'], self.loginInfo['pass_ticket'])
KeyError: 'pass_ticket'
[Finished in 20.1s]

#2018-01-27 13:49:40 January Saturday the 04 week, the 027 day SZ SSMR
C:\Users\z003tesj>pip install json
Collecting json
  Could not find a version that satisfies the requirement json (from versions: )

No matching distribution found for json
解决微信公众号聊天机器人,需要这个json库,但是无法安装
方案:去如下网站下载了simplejson库,或者直接pip simplejson
https://www.lfd.uci.edu/~gohlke/pythonlibs/#simplejson

#2018-01-27 14:08:28 January Saturday the 04 week, the 027 day SZ SSMR
聊天机器人代码如下

import requests
from wxpy import *
import simplejson


#图灵机器人
def talks_robot(info = '你叫什么名字'):
    api_url = 'http://www.tuling123.com/openapi/api'
    apikey = 'a1bbc12dd78b4837b22cd8e98d96e027'
    data = {'key': apikey,
                'info': info}
    req = requests.post(api_url, data=data).text
    replys = json.loads(req)['text']
    return replys

#微信自动回复
robot = Robot()
# 回复来自其他好友、群聊和公众号的消息
@robot.register()
def reply_my_friend(msg):
    message = '{}'.format(msg.text)
    replys = talks_robot(info=message)
    return replys

# 开始监听和自动处理消息
robot.start()

出现如下问题:
█
Traceback (most recent call last):
  File "D:\ST\Python_work\Python_Test.py", line 18, in <module>
    robot = Robot()
NameError: name 'Robot' is not defined
[Finished in 2.1s]
解决方案:
尝试登陆网页版微信和微信公众号也是没用啊
后来换了其他人的代码就可以了



2018-01-22 19:47:23 January Monday the 04 week, the 022 day
D:\EventlogAnalyzer>python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
运行德国人10000行的py文件时候出现问题,我用的Python2.7.14

D:\EventlogAnalyzer>python eventlogAnalyzer.py
Traceback (most recent call last):
  File "eventlogAnalyzer.py", line 19, in <module>
    import wx, os ,re, time, sys,itertools
ImportError: No module named wx

D:\EventlogAnalyzer>

后来我用手机下载wx,返回如下,可能是我的Python2.7.14版本太高了
D:\EventlogAnalyzer>python eventlogAnalyzer.py
Traceback (most recent call last):
  File "eventlogAnalyzer.py", line 19, in <module>
    import wx, os ,re, time, sys,itertools
ImportError: No module named wx

2017-12-17 18:15:08 December Sunday the 50 week, the 351 day
IndentationError: unexpected indent
[Finished in 0.8s with exit code 1]

缩进错误,检查下哪里有问题。

2017-12-17 16:38:07 December Sunday the 50 week, the 351 day
'''
# -*- coding:utf-8 -*- 
#把从CSDN复制的程序放在test.py这个文件里
filename = 'test.py'
#得到新的没有数字和点的文件
filename_new = 'test_new.py'
#打开旧文件
with open(filename) as file_object:
	#得到文件里所有行
	lines = file_object.readlines()
	循环取出文件里的每行
	for line in lines:
		#删除每行的前三个字符,也就是删除数字和点。
		new_line = line[3:]
		#把删除后的行依次放入新文件里面,如果新文件不存在就自动创建该文件。
		open(filename_new,'a').write(new_line)
'''
open(test.py,'a').write('99.')

问题如下:名字无法识别,我写了上百行代码都没事,这次就出问题了
Traceback (most recent call last):
  File "D:\Sublime_work_D\Python_work\dafeng.py", line 1, in <module>
    open(test.py,'a').write('99.')
NameError: name 'test' is not defined
[Finished in 0.8s]
解决方案:给test.py加上引号就行了,


Traceback (most recent call last):
  File "D:\Sublime_work_D\Python_work\article.py", line 9, in <module>
    lines = file_object.readlines()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 21: illegal multibyte sequence
[Finished in 1.0s with exit code 1]

解决办法:删除了复制代码test.py里面的汉字,通过判断#标志,删除对应行就行。

在Python处理字符编码时出现如下错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xb1 in position 0: invalid start byte

此种错误,有几种可能: 
(1)要处理的字符串本身不是gbk编码,但是你却以gbk编码去解码 
比如,字符串本身是utf-8的,但是你却用gbk去解码utf-8的字符串,所以结果不用说,则必然出错

则必然会出现这类的错误,说是,用gbk的方式去解码字符串,想要获得Unicode字符串,但是结果却解码出错了

解决办法:

如果你确定当前字符串,比如抓取网页通过charset=utf-8,已经确定html的字符串是utf-8的,

则可以直接去通过utf-8去解码。


具体业务场景如下:

我读入一个编码为GBK的文件,解析里面的汉字,使用utf-8编码进行正则匹配,出现上述问题

解决方法:

设置python编码为GBK
 #encoding=utf8
 import sys
 reload(sys)
 sys.setdefaultencoding('gbk') 


python xml处理中文时出现的错误,记录一下,以免忘记

 

"UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)"

解决办法,在该python文件的前面加上如下几句,问题得到解决。

import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)




2017-12-17 16:38:04 December Sunday the 50 week, the 351 day
1.py文件总是经常有这个问题,could not convert string to float: 'vertex'
查证后发现linedatas中竟然还有vertex这个字符串存在,也就是strip('vertex ')没有起到应有的作用。
	line_datas = line.strip('vertex ')#.strip().split()

  File "D:\Sublime_work\Python_work\stl2xml_simple.py", line 62, in get_body_xml
    data =float(line_data)/1000				#divie 1000 for each number in vertex line
ValueError: could not convert string to float: 'vertex'
[Finished in 0.9s with exit code 1]
方案:最后换了其他的删除字符方式解决了问题
2017-12-17 16:37:59 December Sunday the 50 week, the 351 day
2
from .models import Topic
#2017-08-01 17:34:06
from .forms import TopicForm

    from .forms import TopicForm
ModuleNotFoundError: No module named 'learning_logs.forms'

    from .forms import TopicForm
ModuleNotFoundError: No module named '__main__.forms'; '__main__' is not a package
[Finished in 1.3s with exit code 1]

    from .models import Topic
SystemError: Parent module '' not loaded, cannot perform relative import

    from django.forms import TopicForm
ImportError: cannot import name 'TopicForm'



1

1

认识你是我们的缘分,同学,等等,记得关注我。

微信扫一扫
关注该公众号

猜你喜欢

转载自blog.csdn.net/BTUJACK/article/details/83308100