In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you the "example analysis of Python 3.x trample", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of Python 3.x treadmill".
There are pits everywhere. File reading open# We open the file using the open method xml = open ("demo.xml") # when using the open command to read the file, there are often the following errors Traceback (most recent call last): File "TempConvert.py", line 84, in for line in xml:UnicodeDecodeError: 'gbk' codec can't decode byte 0x8d in position 38: illegal multibyte sequence# the reason for this error is that the system opens the encoding by default and the file is inconsistent You need to open it with format parameters # for example, if the file is in utf-8 format, you need to use the following format parameters: xml = open ("demo.xml", encoding= "utf-8") 2. Regular expressions\ S and\ S
First, a question is raised by using regular expressions to get a list of mailboxes in a string. Example: A message from csev@umich.edu to cwen@iupui.edu about meeting @ 2PM
# We can use a simple regular expression, regardless of other complex conditions import restr ='A message from csev@umich.edu to cwen@iupui.edu about meeting @ 2PM'lst1 = re.findall ('\ swords @\ slots, s) print (lst1) # ['csev@umich.edu',' cwen@iupui.edu'] # however, we find that The following regular expression has the same result: lst2 = re.findall ('\\ slots @\\ slots, s) print (lst2)
This is strange because in regular expressions in other languages,\ S and\ S represent different meanings,\ S represents a non-empty character, and\ S represents the matching string\ S, so we try the following:
'\ S' ='\\ S' # Truelen ('\ S') # 2len ('\ S') # 2
Are you stunned? So I tried again.
'\ s' ='\\ s' # Truelen ('\\ s') # 2len ('\ s') # 2'\ n' = ='\\ n' # Falselen ('\ n') # 2len ('\ n') # 1
We found that\ s and\ nthe situation is not the same, through a query, found the following article:
Python regex's'vs'\ s'
It is mentioned in the article
Don't confuse python-level string-escaping and regex-level string-escaping. Since s is not an escapable character at python-level, the interpreter understand a string like\ s as the two characters\ and s. Replace s with n, and it understands it as the newline character.
Don't confuse string escape in Python with string escape at the regular expression level. Since s is not an escapable character in Python, the interpreter interprets a string such as\ s as two characters\ and s. Replace s with n, which it understands as a newline character.
Although there is no mention of a more authoritative statement, it also reflects that if it is\ s, it will be regarded as two characters, and if it is\ s because it is an escapable character, it will be regarded as\ one character, and\ s will be regarded as\ s two characters. That's why this happened.
'\ s' ='\\ s'# True3. Regular expression matching method match
When learning the regular expression matching rules, it is found that the way of Python regular matching is slightly different from other ones, such as the problems of\ S and\ S mentioned in the previous item, and then the following:
The regular match of Python is to match from scratch, for example, if we want to match a phone number in a string
In JS, you can use the following regular matches
/ / using JS, we can write as follows: 'don't tell anyone my mobile phone number is 15900000000, or I'll tell someone your number is 13900000000000. Match (/ 1 [0-9] {10} / g) / / (2) [' 15900000000000000']
But it doesn't work so well if you put the same rules in Python.
Import restr ='my mobile phone number is 15900000000, don't tell anyone, or I will tell others your number is 13900000000'# wrong words mah = re.match ('1 [0-9] {10}', str) print (mah) # None
Because the matching match of Python is matched from the beginning by default, and 1 is not necessarily the first letter of a given string.
# another method, findall, should be used instead of mah = re.findall ('1 [0-9] {10}', str) print (mah) # ['159000000000,' 139000000']
From this point, it can be seen that many libraries of Python provide methods that are different from other languages. As partners who transfer to Python in other languages, they should actually test the method or use it when they are familiar with it, rather than thinking without thinking, and wishful thinking that Python is just like other languages.
4. Help documentation pydoc
Help viewing libraries or methods in Python can be done in the following ways:
[optional] enter python in the command line environment to enter the Python compilation environment
Use dir (libraries, objects) to look at the methods that libraries or objects can provide
Dir ('string') # check the string manipulation methods import redir (re) # check the regular expression library operation methods
Use help (library, object) to view the help information of a library or object
Import rehelp (re) # View the help documentation of the regular expression library dir (re.match) # View the help information of `match` of the regular expression
If we want to write the help document to a text file, we can use the command on the command line:
# the help information of the re library can be exported to the text file python-m pydoc re > d:\ re.txt in the following ways under the html document python-m pydoc-w re# windows
For more information about pydoc, please refer to the official document pydoc.
5. String encode base64 encoding
In some tutorials, the base64 encoding of strings is as follows:
Str = "this is string example.wowned output!"; print "Encoded String:" + str.encode ('base64','strict') # expected output result Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
But this code will report an error:
LookupError: 'base64' is not a text encoding; use codecs.encode () to handle arbitrary codecs
It is understood that this wrong way of writing actually comes from the writing method of Python 2.x, but the writing method has changed in Python 3.x. The correct base64 encoding of the string should be:
Import base64str = "this is string example.wowned object!" # returns the version of the original string encoded as a byte string object strb = str.encode () base64b = base64.b64encode (strb) base64 = base64b.decode () print (base64) 6. Python calls C# dynamic link library
Baidu searched a lot of ways for Python to call C# dynamic link library, mostly with the following code:
Import clr# clr.FindAssembly ('DotNetWithPython.dll') # dll in the current directory clr.AddReferenceToFile (' DotNetWithPython.dll') # dll imports all classes in the dynamic link library in the current directory from DotNetWithPython import * # if _ _ name__ = ='_ main__': mainapp = MainForm () # initializes the MainForm class object
Unfortunately, there is no normal use, I do not know exactly what went wrong, why there is no effect, is it difficult that these are the uses of Python 2.x? (I studied Python 3.x)
The following thoughts were made:
Python's clr is PythonNet, so do you want to go directly to the PythonNet official or github to find the relevant code?
So I searched for the following address: pythonnet.github.io/ tried one by one according to the code given in it, starting with this:
From System import Stringfrom System.Collections import *
We find that we will report an error:
Traceback (most recent call last):
File "d:/Temp/PythonProjects/Demos/DllDo.py", line 10, in
From System import String
ModuleNotFoundError: No module named 'System'
We try to modify the code to:
Import clrfrom System import Stringfrom System.Collections import *
To be sure, our calls to .NET-related classes have to import clr and we keep trying when we try the following code:
Import clrfrom System.Drawing import Pointp = Point (5,5)
Wrong report again:
D:/Temp/PythonProjects/Demos/DllDo.py:11: DeprecationWarning: The module was found, but not in a referenced namespace.
Implicit loading is deprecated. Please use clr.AddReference ('System.Drawing').
From System.Drawing import Point
From the error message given, we can see that we need to reference the space:
Import clrclr.AddReference ('System.Drawing') from System.Drawing import Pointp = Point (5,5) print (p) # {Xerox 5
At this point, we are basically sure that there is no problem for Python to call C #, so what if we can call the self-defined dll dynamic link library? We try to follow the reference method of the previous system class:
Import clrclr.AddReference ('DotNetWithPython') from DotNetWithPython import MainFormmainapp = MainForm ()
An error was reported as a result:
Traceback (most recent call last):
File "d:/Temp/PythonProjects/Demos/DllDo.py", line 12, in
From DotNetWithPython import MainForm
ModuleNotFoundError: No module named 'DotNetWithPython'
So I thought:
Clr can call the class objects provided by .NET itself normally, but the difference between the dynamic link library written by myself and that provided by .NET itself is that it is not in the system environment, and its own dll is in the current directory or other directory.
So we used dir (clr) to determine if there were any methods available
Import clrdir (clr) # ['AddReference',' FindAssembly', 'GetClrType',' ListAssemblies', 'Microsoft',' Python', 'System',' _ AtExit','_ class__','_ _ doc__','_ _ file__','_ _ loader__','_ name__','_ package__','_ spec__','_ version__','_ extras', 'clrModule' 'NativeCallers, 'getPreload',' setPreload', clrmethod', 'clrproperty',' estrangement]
We found that the method FindAssembly feels similar, so we test it according to the previous reference to the system class and this sentence:
Import clrclr.FindAssembly ('DotNetWithPython.dll') clr.AddReference (' DotNetWithPython') from DotNetWithPython import MainFormmainapp = MainForm ()
The same mistake made me cry, so I had to go to PythonNet Github's issues to find the answer. I found that many people asked this question, and the question was locked in .net core, .net 5, but there was no such problem in .net Framework, so I built a new project based on .net Framework 4.x to conduct a simple test and found that there was no error.
Now the problem is clear, but it hasn't been solved, so I can only read the difficult issues list one by one. I found this post, issues 1536, and gave a clear statement, Pythonnet 2.5 does not support .NET 5, It is supported in v3 previews.
Okay, so I used pip list to check the versions of all the Python third-party libraries
C:\ Users\ Administrator > pip list
Package Version
--
Click 7.1.2
Pip 22.0.3
Pycparser 2.21
PyQt5 5.15.4
Pyqt5-plugins 5.15.4.2.2
PyQt5-Qt5 5.15.2
PyQt5-sip 12.9.1
Pyqt5-tools 5.15.4.3.2
Python-dotenv 0.19.2
Pythonnet 2.5.2
Qt5-applications 5.15.2.2.2
Qt5-tools 5.15.2.1.2
Setuptools 41.2.0
Sure enough, the version of pythonnet is 2.5.2. I downgraded the project and found that. Net core is only supported when the version is net core 1.x, and neither 2.x-3.x nor .NET 5 supports it.
So if you are using pythonnet 2.x, don't try to use a later version of. Net core to implement your functionality, otherwise you need to update pythonnet to a later version.
Continue to look at issues 1536, found that even the updated version will still have problems, and traced to issues 1473 I tried to upgrade pythonnet to 3.x previews version, but the error, did not upgrade successfully, so did not continue to test the subsequent features.
The above is all the contents of this article "example Analysis of Python 3.x treading pit". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.