Tag Archives: python error

[>]

1. Questions 

[<twisted.python.failure.Failure < class  ' OpenSSL.SSL.Error ' >>]

solution:

If it is under Windows, the corresponding version of pyOpenSSL needs to be additionally installed. For example, pyOpenSSL- 0.13 .winxp32-py2. 7 .msi; if it prompts that there are no compiled files, you may also need to install mingwg. 
If it is under Linux, it is very simple, just pip install scrapy directly, it will automatically install the dependent package twisted. Using the same command under windows will cause the above problem, so additionally install the corresponding software.

 

[Solved] Python Selenium Error: AttributeError: ‘WebDriver‘ object has no attribute ‘find_element_by_xpath‘

Python selenium Error:

el = driver.find_element_by_xpath('//*[@id="changeCityBox"]/ul/li[2]/a')
driver.find_element_by_xpath('//*[@id="search_input"]').send_keys('python',Keys.ENTER)

Solution: Modify the codes above to:

from selenium.webdriver.common.by import By
el = driver.find_element(By.XPATH,r'//*[@id="changeCityBox"]/ul/li[2]/a')
driver.find_element(By.XPATH,r'//*[@id="search_input"]').send_keys("python",Keys.ENTER)

War here to use the browser driver for Google, other browsers can also be Edge to edge, modify the driver needs to configure the environment

from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys   # Button commands for the keyboard
from selenium.webdriver.common.by import By
driver = Chrome()
driver.get("https://www.lagou.com/")
# Find the element copyxpath that the browser needs to operate on
el = driver.find_element(By.XPATH,r'//*[@id="changeCityBox"]/ul/li[2]/a')
# el = driver.find_element_by_xpath('//*[@id="changeCityBox"]/ul/li[2]/a')
el.click() # Click event
# find the input box F12 element copyxpath, enter python content, enter or search button xpath
driver.find_element(By.XPATH,r'//*[@id="search_input"]').send_keys("python",Keys.ENTER)
# driver.find_element_by_xpath('//*[@id="search_input"]').send_keys('python',Keys.ENTER)

Python Error: ImportError: cannot import name ‘logsumexp’ from ‘scipy.misc’(Anaconda3\lib\site-packages\scipy\misc)

How to Solve Error:

ImportError: cannot import name ‘logsumexp’ from ‘scipy.misc’(Anaconda3\lib\site-packages\scipy\misc)
or
ImportError: cannot import name ‘comb’ and ‘logsumexp’

Directly go in and change the code inside the genisim package, but it is best not to change it indiscriminately. The reason is that there is no logsumexp after the update of scipy.misc package, the author I changed a code inside genisim.
Modify the following codes in ldamodel.py
from scipy.misc import logsumexp
to
from scipy.special import logsumexp
The approximate path is shown below, my gensim==3.0.1 is this version. But this error is also related to the version. I can see that there is a problem with line 56 of ldamodel.py in the gensim package, which should be updated.

Python Error: [9880] failed to execute script [How to Solve]

1. When I was packing the game, the exe in dist flashes back. You can’t see what the error is.

After recording the screen with the video recorder, the error code is found as follows:

2. According to the error content, scoreboard There is a problem with line 18 of Py:

The cause of the error has been highlighted.

3. Problem-solving:

It is in the font setting “None”, can not be translated, so lead to error, change the “None” to the system font, here changed to ‘SimHei’

When checking the information, I found that other people encountered the problem: the path of the image. The relative path written is not correct, you have to write the absolute path.)

PS: At this point the game can still only be used on your own computer, also because of the picture path problem. The path on your own computer is not the same as the path on other people’s computers. To let others play too, you still have to change it.

Python Error: SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3:

Reason: Window can read files with \, but in the string \ is used as an escape character, after the escape may not find the path of the resource, for example \t will be escaped as tab key

Upper Code:

>>> def func1(path_name):
...     import os
...     if os.path.exists(path_name):
...         return "True"
...     else:
...         return "False"
...
>>> func1("C:\Users\renyc")#error
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>>
In this example: "C:\Users\renyc" is escaped and the resource of the path is not found.

Solution:

>>> def func1(path_name):
...     import os
...     if os.path.exists(path_name):
...         return "True"
...     else:
...         return "False"
...
>>> func1(r"C:\Users\renyc")#Add r to declare the string without escaping
'True'
>>> func1("C:\\Users\\\renyc")# handling of absolute paths
'True'
>>>

 

There are three ways to summarize.

One:Replace the write method with an absolute path func1(“C:\Users\renyc”)

Two: explicitly declare the string without escaping (add r) func1(r “C:\Users\renyc”)

III:Use Linux paths/ func1(“C:/Users/renyc”)

[Solved] Python Error: positional argument follows keyword argument

Syntax error: position argument follows keyword argument
syntax error: position parameter follows keyword parameter
error example </ font>

def sub(a, b):
    return

s3 = sub(a = 9, 3)
s4 = sub(b = 9, 3)

When a function is called, an error will be reported if the parameter passed (····, formal parameter = argument, argument, ······) occurs
solution:
make the following modifications

def sub(a, b,):
    return
s0 = sub(9,3)
s1 = sub(a=9, b=3)
s2 = sub(9, b = 3)

[Solved] Python Error: local variable ‘var‘ referenced before assignment

Unboundlocalerror: local variable ‘var’ referenced before assignment
local variable “var” referenced before assignment

error example 1

var = 10
def f1():
    print(var)
    var = 2
    print(var)
f1()

When VaR is a global variable, it is modified and undeclared in the function

solution:
declare the global variable Global var  before calling

error example 2 

def f2():
    var = 0
    def f3():
        var *= 0
        return var
    return f3()
f2()

VaR is a local variable defined in F2. Its value is modified in nested functions and is not declared
solution:
declare nonlocal var  in nested functions in advance

[Solved] Python Error: TypeError: write() argument must be str, not bytes

In the chapter “decision tree” of “machine learning in action”, the error typeerror: write() argument must be STR, not bytes is first prompted in the stored procedure of learning decision tree. The error message is that the parameter of write() function must be STR, not byte. I don’t understand. Look at the source code. There is an error. There is an error in compiling the sentence pickle. Dump (inputtree, FW). Let’s first look at the usage of pickle. Dump()

From the penultimate sentence, we can see that our problem lies in the variable FW, that is, the statement FW = open (file name, ‘W’). That is to say, the type of the variable FW should be bytes, so you can change ‘W’ to ‘WB’ and compile it successfully after modification. The same principle prompts Unicode decodeerror: ‘GBK’ codec can’t decode byte 0x80 in position 0: illegal multibyte sequence error, because the previously saved TXT file is written in binary, so binary should also be used when reading, Fr = open (filename) in the read file should be changed to fr = open (filename, ‘RB’). OK, problem solved! Under the test:

success!

target is multiclass but average=’binary’. please choose another average setting.

When the sklearn model is referenced and the model is evaluated after fit, the error occurs. The code is as follows:

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import f1_score

regressor = DecisionTreeClassifier(random_state=42)
regressor.fit(X_train,y_train)
y_pred = regressor.predict(X_test)

print(f1_score(y_pred,y_test))

After running, it appears:

target is multiclass but average='binary'. please choose another average setting.

In fact, there is no problem with the code. The problem lies in the data type, y here_ The values in test are not binary of 0 and 1, but [123, 23142243 ]Therefore, in essence, it is impossible to carry out hair care_ Score calculation, you will find that if F1_ Change score to accuracy_ Score, the return result is 0
so to predict y of this kind of value type, other evaluation indicators, such as R 2, are needed. The code is as follows:

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import r2_score
regressor = DecisionTreeClassifier(random_state=42)
regressor.fit(X_train,y_train)

# TODO: output predicted scores on the test set
y_pred = regressor.predict(X_test)

print(r2_score(y_pred,y_test))

result:

0.12800402751210926

Python Error aiohttp.client_exceptions.ClientConnectorCertificateError, Cannot connect to host:443

An error is reported by the python connection interface
as follows:

aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to  host:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1056)')]

SSL handshake failed on verifying the certificate
protocol: <asyncio.sslproto.SSLProtocol object at 0x000000B1D4E2A7F0>
transport: <_SelectorSocketTransport fd=708 read=polling write=<idle, bufsize=0>>

Solution:

# conn = aiohttp.TCPConnector(verify_ssl=False)  # Prevent ssl from reporting errors
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=64,verify_ssl=False)) as session:

Add verify_ SSL = false.

Python errors: valueerror: if using all scalar values, you must pass an index (four solutions)

 

1. Error scenarios:

import pandas as pd
dict = {'a':1,'b':2,'c':3}
data = pd.DataFrame(dict)

2. Error reason:

When passing in the dictionary with nominal attribute value directly, you need to write index, that is, you need to set index when creating the dataframe object.

3. Solution:

It is a common requirement to create dataframe objects through dictionaries, but there may be different writing methods for different object forms. Looking at the code, the following four methods can correct this error and produce the same correct results. Just choose which method to use according to your own needs.

import pandas as pd

#Method 1: Directly set the index when creating the DataFrame
dict = {'a':1,'b':2,'c':3}
data = pd.DataFrame(dict,index=[0])
print(data)

#Method 2: Convert the dictionary with value as nominal variable to DataFrame object by from_dict function
dict = {'a':1,'b':2,'c':3}
pd.DataFrame.from_dict(dict,orient='index').T
print(data)

#Method 3: When entering the dictionary, do not let the Value be the nominal property, convert the Value to a list object and then pass it in.
dict = {'a':[1],'b':[2],'c':[3]}
data = pd.DataFrame(dict)
print(data)

#Method 4: directly take out the key and value, are converted to list objects
dict = {'a':1,'b':2,'c':3}
pd.DataFrame(list(dict.items()))
print(data)