1. 程式人生 > >共享個人整理的Python問題,有原始碼,分析過程,解決方案,還有時間戳做間隔

共享個人整理的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:
	#得到