Category Archives: Python

[Solved] Python import module error: importerror: no module named mysql.connector

The version of Python is

$ python --version
Python 2.7.12

The error code is as follows

importmysql.connector

The error message is

ImportError:Nomodulenamedmysql.connector

The driver installed at the beginning is that the installation was successful

$ pipinstallmysql-connector

But if you install MySQL connector python, you will report an error

Collecting mysql-connector-python
  Could not find a version that satisfies the requirement mysql-connector-python (from versions: ) No matching distribution found for mysql-connector-python

So now the driver is MySQL connector instead of MySQL connector Python
ask for help from an experienced friend

The problem has been solved

The steps are as follows:

Execute PIP search MySQL connector | grep -- color MySQL connector Python

The output is like this

mysql-connector-python-rf (2.1.3)        - MySQL driver written in Python mysql-connector-python (2.0.4) - MySQL driver written in Python

Usepip install mysql-connector-python-rf==2.1.3 is ok

python Warning: OverflowError: Python int too large to convert to C long

Once, when using ORM to perform a join table query, there was a problem with Python int too large to convert to C long

After analyzing the error, the last prompt of the error is as follows:

File "F:\python\python3.6\lib\sqlite3\dbapi2.py", line 64, in convert_date
    return datetime.date(*map(int, val.split(b"-")))

When viewing my model.py file, my model definition is as follows:

from django.db import models


# Create your models here.

class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=64)
    publishDate = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE)

    authors = models.ManyToManyField(to="Author")


class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    AuthorDetail=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    nid = models.AutoField(primary_key=True)
    # birthday = models.DateField()  # In particular, this line is commented out so that it no longer prompts Python int too large to convert to C long
    tetephone = models.BigIntegerField()
    addr = models.CharField(max_length=64)


class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()

Python: `if not x:` VS `if x is not None:` VS `if not x is None:`

There are three main ways to judge whether a variable is none in code

The first is’ if x is none ‘

The second is’ if not X: ‘

The third is “if not x is none”

If you think it doesn’t make any difference, you should be careful. There is a hole in it. Let’s look at the code first

>>>x=1
>>>notx
False
>>>x=[1]
>>>notx
False
>>>x=0
>>>notx
True
>>>x=[0]#Youdon'twanttofallinthisone.
>>>notx
False

In Python, none, false, empty string “” 0, empty list [, empty dictionary {}, empty tuple () are equivalent to false, that is:

<strong>notNone==notFalse==not''==not0==not[]==not{}==not()</strong>

Therefore, when using the list, if you want to distinguish between X = = [] and x = = none, there will be a problem with ‘if not X:’:

>>>x=[]
>>>y=None
>>>
>>>xisNone
False
>>>yisNone
True
>>>
>>>
>>>notx
True
>>>noty
True
>>>
>>>
>>>notxisNone
>>>True
>>>notyisNone
False
>>>

Maybe you want to judge whether x is none or not, but you also judge the case of ‘x = =]’, in which case you will not be able to distinguish

for those who are used to using the writing method of if not x, it must be clear that when x equals none, false, empty string “” 0, empty list [], empty dictionary {}, empty tuple (), it will not affect your judgment

As for the writing of ‘if x is not none’ and ‘if not x is none’, it is obvious that the former is clearer, while the latter may make readers misunderstand it as’ if (not x) is none ‘, so the former is recommended, which is also the style of Google recommendation
at the same time

conclusion:

‘if x is not none’ is the best way to write. It is clear and will not make mistakes. I will insist on using this way in the future

the premise of using if not x is: it must be clear that when x equals none, false, empty string “” 0, empty list [], empty dictionary {}, empty tuple (), it will not affect your judgment

================================================================

However, this does not apply to the case where the variable is a function, which is reproduced from: https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md

The difference between foo is none and foo = = none

Question link

if foo is None: pass
if foo == None: pass

If the same object instance is compared, is always returns true and = = depends on “ EQ ()”

>>> class foo(object):
    def __eq__(self, other):
        return True

>>> f = foo()
>>> f == None
True
>>> f is None
False

>>> list1 = [1, 2, 3]
>>> list2 = [1, 2, 3]
>>> list1==list2
True
>>> list1 is list2
False

In addition

(ob1 is ob2) IS (id(ob1) == id(ob2))

################################################################################

Supplement, 2013.10.09

What does not mean in Python?For example, thank you very much

In python not is a logical judgment word for boolean True and False, not True for False and not False for True. Here are a few common uses of not.
(1) not is used in conjunction with the logical judgment sentence if, representing the statement after the colon is executed when the expression after not is False. For example
a = False
if not a: (Here, because a is False, not a is True)
    print "hello"
Here we can output the result hello
(2) Determine whether the element is in the list or dictionary, if a not in b, a is the element, b is the list or dictionary, this sentence means that if a is not in the list b, then execute the statement after the colon, for example
a = 5
b = [1, 2, 3]
if a is not in b:
    print "hello"
The result hello can also be output here
not x is equivalent to     if x is false, then True, else False

Python Attempted relative import in non-package,ImportError: cannot import name ‘xx’ from ‘__main

Problem introduction

When writing a python script, you want to extract the configuration shared by the two scripts to form a configuration file, and read the configuration file when running the script

Script tool directory structure:

	programoperater
		__init__.py
		autorun_startprogram.py		
		autorun_checkstart.py	
		programsetting.py	

In the script, import the configuration file through the relative path:

from . import programsetting

In the server, use your own installed Python 3.7.3 to report an error:

use the server’s own Python 2.7.5 to report an error:

Problem analysis, that is, python package mechanism

Official explanation: relative imports use a module’s name attribute to determine that module’s position in the package hierarchy__ name__ To achieve

Through “from. Import programsetting g”, programsetting obtains the “programoperator. Program”__ name__ Property. The premise is that the program operator is recognized by the Python interpreter as a package for processing (for example, run.py running in the peer folder of the program operator has statements such as import program operator. Program)

newfolder/
└─ programoperater
│		__init__.py
│		autorun_startprogram.py	
│		autorun_checkstart.py	
│		programsetting.py		
│
└─ run.py

there is a problem that causes me to quote packages:
scripts that I run directly will be regarded as top-level scripts. Top level script__ name__ Is automatically set to__ main__。 So if I run autorun directly from inside the program operator folder_ Checkstart. Py, then its__ name__ It’s set up__ main__, Python will not treat it as a package, and the relative import statement will not work

Note that relative imports are based on the name of the current module. Since the name of the main module is always “main”, modules intended for use as the main module of a Python application must always use absolute imports.

Solutions

change directory structure:

 programoperater
 │ 	 	__init__.py
 │   	autorun_checkstart.py
 │    	autorun_startprograms.py
 │  
 └─settings
         __init__.py
         programsetting.py

modification of package introduction mode:

from settings import programsetting

Through this modification, you can directly run the specified script autorun_ checkstart.py

Interpretation of the Official Website Package Mechanism: https://docs.python.org/zh-cn/3/tutorial/modules.html#packages

How to Solve MySQL-python Install Error:Python version 2.7 required, which was not found in the registry

1. install MySQL-python-1.2.3.win-amd64-py2.7.exe, when prompted: Python version 2.7 required, which was not found in the registry

This is in the registry can not identify python2.7, the reason windows is 64-bit, the installation of Python is 32-bit

Note: MySQLdb for python (32/64 bit) download; http://www.codegood.com/archives/129; different versions are available, choose the py you need

The solution is:
1. Create a new register.py file in any disk folder
Copy the following code into it:

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = “SOFTWARE\\Python\\Pythoncore\\%s\\” % (version)
installkey = “InstallPath”
pythonkey = “PythonPath”
pythonpath = “%s;%s\\Lib\\;%s\\DLLs\\” % (
installpath, installpath, installpath
)

def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError as e:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
except:
print “*** Unable to register!”
return
print “— Python”, version, “is now registered!”
return
if (QueryValue(reg, installkey) == installpath and
QueryValue(reg, pythonkey) == pythonpath):
CloseKey(reg)
print “=== Python”, version, “is already registered!”
return
CloseKey(reg)
print “*** Unable to register!”
print “*** You probably have another Python installation!”

if __name__ == “__main__”:
RegisterPy()

2. Locate the directory where the file is located and run python register.py

3. If you run MySQLdb, it will be automatically recognized and installed successfully

How to Solve Python Error: python __file__ is not defined

 

python __ file__ Is not defined solution

__ file__ It is a variable generated when Python module is imported__ file__ Can’t be used, but what should I do to get the path of the current file

Method 1

import inspect, os.path

filename = inspect.getframeinfo(inspect.currentframe()).filename
path     = os.path.dirname(os.path.abspath(filename))

Method 2

import inspect
import os

os.path.abspath(inspect.getsourcefile(lambda:0))

Link: https://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python/18489147#18489147

Python: How to Solve raise JSONDecodeError(“Expecting value”, s, err.value) from None json.decoder…

When dealing with the local JSON file, because of the change of the JSON format, the code can not run and the error occurs. Here are the solutions:

[initial code]

with open(path,'r') as f:
    a = json.loads(f.read())
    print(a)
    print(type(a))

[prompt error]

Traceback (most recent call last):
  File "C:\Users\14062\Desktop\json02.py", line 25, in <module>
    c = json.loads(b)
  File "C:\Users\14062\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\14062\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\14062\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

[solution]

with open(path,encoding='utf-8-sig', errors='ignore') as f:
     data = json.load(f, strict=False)
     print(data)

Python scikit-learn (metrics): difference between r2_score and explained_variance_score?

I noticed that that ‘r2_score’ and ‘explained_variance_score’ are both build-in sklearn.metrics methods for regression problems.

I was always under the impression that r2_score is the percent variance explained by the model. How is it different from ‘explained_variance_score’?

When would you choose one over the other?

Thanks!

OK, look at this example:

In [123]:
#data
y_true = [3, -0.5, 2, 7]
y_pred = [2.5, 0.0, 2, 8]
print metrics.explained_variance_score(y_true, y_pred)
print metrics.r2_score(y_true, y_pred)
0.957173447537
0.948608137045
In [124]:
#what explained_variance_score really is
1-np.cov(np.array(y_true)-np.array(y_pred))/np.cov(y_true)
Out[124]:
0.95717344753747324
In [125]:
#what r^2 really is
1-((np.array(y_true)-np.array(y_pred))**2).sum()/(4*np.array(y_true).std()**2)
Out[125]:
0.94860813704496794
In [126]:
#Notice that the mean residue is not 0
(np.array(y_true)-np.array(y_pred)).mean()
Out[126]:
-0.25
In [127]:
#if the predicted values are different, such that the mean residue IS 0:
y_pred=[2.5, 0.0, 2, 7]
(np.array(y_true)-np.array(y_pred)).mean()
Out[127]:
0.0
In [128]:
#They become the same stuff
print metrics.explained_variance_score(y_true, y_pred)
print metrics.r2_score(y_true, y_pred)
0.982869379015
0.982869379015

So, when the mean residue is 0, they are the same. Which one to choose dependents on your needs, that is, is the mean residuesupposeto be 0?

Most of the answers I found (including here) emphasize on the difference betweenR2andExplained Variance Score, that is:The Mean Residue(i.e. The Mean of Error).

However, there is an important question left behind, that is: Why on earth I need to consider The Mean of Error?


Refresher:

R2: is theCoefficient of Determinationwhich measures the amount of variation explained by the (least-squares) Linear Regression.

You can look at it from a different angle for the purpose of evaluating thepredicted values ofylike this:

Varianceactual_y × R2actual_y = Variancepredicted_y

So intuitively, the more R2is closer to1, the more actual_y and predicted_y will havesamevariance (i.e. same spread)


As previously mentioned, the main difference is theMean of Error; and if we look at the formulas, we find that’s true:

R2 = 1 - [(Sum of Squared Residuals/n)/Variancey_actual]

Explained Variance Score = 1 - [Variance(Ypredicted - Yactual)/Variancey_actual]

in which:

Variance(Ypredicted - Yactual) = (Sum of Squared Residuals - Mean Error)/n

So, obviously the only difference is that we are subtracting theMean Errorfrom the first formula! …But Why?


When we compare theR2Scorewith theExplained Variance Score, we are basically checking theMean Error; so if R2= Explained Variance Score, that means: The Mean Error =Zero!

The Mean Error reflects the tendency of our estimator, that is: theBiased v.s Unbiased Estimation.

 

Python calculator error: can’t multiply sequence by non-int of type ‘float’

Example:

num1=input('input the first num: ')

num2=input('input the second num: ')
num3=num1*num2
print(num3)

After execution, the result is: input the first num: at this time, enter the integer on the keyboard and press enter

Input the second num: enter the integer again and press enter

Can’t multiply sequence by non int of type ‘float’

Reason: the input() function inputs a string format, so the integer you enter on the keyboard is not a positive integer, but a string format. Therefore, when executing the statement Num3 = num * num, an error will be reported. Because num1 and num2 are both strings, they cannot be multiplied

Solution: convert num1 and num2 into integers

Specific solutions

1. The third line of the code is changed to: Num3 = int (num1) * int (num2)

2. Change the first and second lines to: num1 = int (input (‘input the first num: ‘)

num2=int(input(‘input the first num: ‘))