Tag Archives: python error

Python opens the table and appears pandas.errors.ParserError: Error tokenizing data. C error:

CSV files are delimited by commas by default, but commas are used a lot in Chinese, so when writing to CSV, Pandas can set the splitter symbol sep= ‘\t’, which is tab-delimited.
that such read behind the CSV data processing, must remember to add a parameter delimiter:

path = r"Your input path and file"
data = pd.read_csv(path,delimiter="\t")
``

Pychar can’t connect to Python console, but it can run. Py file, and Anaconda’s command line can run Python command

Error:
Traceback (most recent call last):
File “D:\PyCharm Edu 2020.3.3\plugins\python-ce\helpers\pydev\pydevconsole. py”, line 5, in
from _pydev_comm. pydev_rpc import make_rpc_client, start_rpc_server, start_rpc_server_and_make_client
File “D:\PyCharm Edu 2020.3.3\plugins\python-ce\helpers\pydev_pydev_comm\pydev_rpc. py”, line 4, in
from _pydev_comm. pydev_server import TSingleThreadedServer
File “D:\PyCharm Edu 2020.3.3\plugins\python-ce\helpers\pydev_pydev_comm\pydev_server. py”, line 4, in
from _shaded_thriftpy. server import TServer
File “D:\PyCharm Edu 2020.3.3\plugins\python-ce\helpers\third_party\thriftpy_shaded_thriftpy\server. py”, line 9, in
from shaded_thriftpy. transport import (
File “D:\PyCharm Edu 2020.3.3\plugins\python-ce\helpers\third_party\thriftpy_shaded_thriftpy\transport_init. py”, line 57, in
from .sslsocket import TSSLSocket, TSSLServerSocket # noqa
File “D:\PyCharm Edu 2020.3.3\plugins\python-ce\helpers\third_party\thriftpy_shaded_thriftpy\transport\sslsocket. py”, line 7, in
import ssl
File “D:\Anaconda\lib\ssl. py”, line 98, in
import _ssl # if we can’t import it, let the error propagate
ImportError: DLL load failed while importing _ssl: The specified program could not be found.

How to Fix this error
Link: https://stackoverflow.com/questions/54175042/python-3-7-anaconda-environment-import-ssl-dll-load-fail-error
Copy the following files from anaconda\Library\bin to anaconda/DLLs
libcrypto-1_1-x64.dlllibssl-1_1-x64.dll

How to Fix Errors encountered in executing Python scripts with command line parameters

Today, when I was learning to execute a Python script with command line parameters, there was an error
ModuleNotFoundError: No module named ‘cv2’ at runtime. The problem has been solved, so I think I can write a note for your reference


import argparse
import cv2 as cv
import imutils
ap=argparse.ArgumentParser()
ap.add_argument('-i','--input',required=True,help='path to input image')
ap.add_argument('-o','--output',required=True,help='path to output image')
args=vars(ap.parse_args())

Then open the console and type

// An highlighted block
$ python shape_counter.py --help

It did not get the result I wanted, so an error was returned, and cv2 (ModuleNotFoundError: No Module named ‘Cv2’) had to be found in the file. I think pycharm and the environment of this machine are independent. I tried to run OpenCV in Pycharm and did not report any mistakes, so they are independent. OpenCV is also installed in the native environment before it can be used.
first open our console
install OpenCV


again error, the yellow part is important information, tell us to upgrade our PIP to 20.2.3 version
upgrade PIP version
command:

python -m pip install --upgrade pip


appears such a page is successfully upgraded
again install OpenCV
command:

python -m pip install opencv-python


install imutils
command:

python -m pip install imutils


ok, now let’s go to our script file and open the console and type:

python shape_counter.py --help

Results:

Python uses try… Except… To output detailed errors

When a Python segment USES try... except... After , I don’t know how to locate the detailed program crush
. These two days, the program needs to use this aspect, so I looked it up.

You need to use the Traceback package

import traceback

try:
		#Dividing by zero errors is an example
		3/0
except Exception, e:
		#This is the output for the error category, which is not really visible if the catch is a generic error
		print 'str(Exception):\t', str(Exception) #Output str(Exception): <type 'exceptions.Exception'>
		#This is the specific reason for the output error. 
		print 'str(e):\t\t', str(e) #output str(e): integer division or modulo by zero
		print 'repr(e):\t', repr(e) # Output repr(e): ZeroDivisionError('integer division or modulo by zero',)
		print 'traceback.print_exc():';    
		#Both of the following steps output the exact location of the error
		traceback.print_exc()
		print 'traceback.format_exc():\n%s' % traceback.format_exc()

In addition, Python 2.6 except after the sentence can be replaced with except Exception as e

Python error: pandas.errors.ParserError: Error tokenizing data. C error: Expected 3……

Error message
When doing data processing in Python, the following error is reported:

pandas.errors.ParserError: Error tokenizing data. C error: Expected 3 fields in line 28, saw 4


The reason for the error
First, let’s take a look at error reporting:

pandas.errors.ParserError: Error tokenizing data. C error: Expected 3 fields in line 28, saw 4

Translation:

Alphaers. errors.parserror: Error marking data. C Error: Three fields are required on line 28, see 4

The error was caused by a data set format error.
The solution
We need to modify the data format or make some Settings in the read-in. The following two methods are feasible:
1. Modify the read-in code
Add the following parameters after reading the code:

error_bad_lines=False #Addition of parameters

2. Modify the file format
I made the error because I was lazy and modified the suffix name directly. The correct way to do this is to open the file in the format required by another existing dataset. For example, I need a CSV file, and the existing file is XLSX. I need to open another CSV file, and the suffix name cannot be directly modified.

Django uses Mysql to report an error loading MySQL DB module: no module named ‘mysqldb’

Reason for error:

The MySQLdb package has been deprecated in python3.

The solution

install pymysql package
pip install PyMySQL 

To take the following directory structure as an example, add the following code to test5/test5/init.py:

import pymysql
pymysql.install_as_MySQLdb()

∎── booktest
∎ ∎── admin.py
∎ ∎── apps.py
∎ ── init.py
∎ ∎── migrations
∎ ∎ ∎── init.py
∎ ∎ └── pycache
∎ ∎── models.py
∎ ∎── pycache
∎ ∎── tests.py
∎ ∎── urls.py
∎ └── views.py
°── manage.py
°── static
∎ └── booktest
∎ └── a1.jpg -> /usr/share/wallpapers/deepin/Flying_Whale_by_Shu_Le.jpg
── templates
∎ └── index.html
└── test5
── init.py
── pycache
── settings.py
──urls.py
└── wsgi.py

Python error: urllib.error.HTTPError : http Error 404: not found

The code is as follows:

import sys
import random
from urllib.request import urlopen
WORD_URL = "http://learncodethehardway.org/word.txt"
WORDS = []
PHRASES = {
    "class %%%(%%%):":
        "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef __init__(self,***)":
        "class %%% has-a __init__ that takes self and *** params.",
    "class %%%(object): \n\tdef ***(self, @@@)":
        "class %%% has-a function *** that takes self and @@@ params.",
    "*** = %%%()":
        "Set *** to an instance of class %%%.",
    "***.*** = @@@":
        "From *** get the *** function, call it with params self, @@@,",
    "***.*** = '***'":
        "From *** get the *** attribute and  set it to '***'."
}
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST = True
else:
    PHRASE_FIRST = False

for word in urlopen(WORD_URL).readlines():
    WORDS.append(str(word.strip(), encoding='utf-8'))
    
def convert(snippet, phrase):
    class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]     
    other_names = random.sample(WORDS, snippet.count("***"))         
  results = []
    param_names = []
    for i in range(0, snippet.count('@@@')):
        param_count = random.randint(1, 3)    
        param_names.append(', '.join(random.sample(WORDS, param_count)))        
    for sentence in snippet, phrase:
        result = sentence[:]
        for word in class_names:
            result = result.replace('%%%', word, 1)     
        for word in other_names:
            result = result.replace('***', word, 1)     
        for word in param_names:
            result = result.replace('@@@', word, 1)     
        results.append(result)
    return results

try:
    while True:
        snippets = list(PHRASES.keys())    
        random.shuffle(snippets)        
        for snippet in snippets:
            phrase = PHRASES[snippet]      
            question, answer = convert(snippet, phrase)   
            if PHRASE_FIRST:
                question, answer = answer, question
            print(question)
            input("> ")
            print(f"ANSWER:  {answer}\n\n")

  except EOFError:
      print("\nBye")

Error message:

Traceback (most recent call last):
  File "E:/python/ex41.py", line 30, in <module>
    for word in urlopen(WORD_URL).readlines():
  File "D:\pycharm\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "D:\pycharm\lib\urllib\request.py", line 531, in open
    response = meth(req, response)
  File "D:\pycharm\lib\urllib\request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "D:\pycharm\lib\urllib\request.py", line 563, in error
    result = self._call_chain(*args)
  File "D:\pycharm\lib\urllib\request.py", line 503, in _call_chain
    result = func(*args)
  File "D:\pycharm\lib\urllib\request.py", line 755, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "D:\pycharm\lib\urllib\request.py", line 531, in open
    response = meth(req, response)
  File "D:\pycharm\lib\urllib\request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "D:\pycharm\lib\urllib\request.py", line 569, in error
    return self._call_chain(*args)
  File "D:\pycharm\lib\urllib\request.py", line 503, in _call_chain
    result = func(*args)
  File "D:\pycharm\lib\urllib\request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found