In Python, Uincode string processing has always been a confusing problem. Many Python enthusiasts are often confused about the differences between Unicode, UTF-8, and many other encodings. This article describes how to process Unicode and Python in Chinese. Let's take a look at the following small series. in Python, Uincode string processing has always been a confusing problem. Many Python enthusiasts are often confused about the differences between Unicode, UTF-8, and many other encodings. This article describes how to process Unicode and Python in Chinese. Let's take a look at it with the small editor.
In Python, Uincode string processing has always been a confusing problem. Many Python enthusiasts are often confused about the differences between Unicode, UTF-8, and many other encodings. I used to be a member of this "brainstorming group", but after more than half a year of hard work, I finally figured out some of these relationships. Now I will sort it out as follows and share it with my colleagues. At the same time, I hope to use this short article to attract more real experts to join us and improve our Python Chinese environment.
Some of the ideas mentioned in this article are obtained by reading the data, and some are obtained by the author using the "speculation and verification" method based on the existing encoding data. I asked myself to learn from each other, for fear of having many mistakes. You can see that there are no lack of experts in the government. if any of them finds any mistakes, I hope you will not be enlightened. I am a little ugly, and my point of view is wrong. so you don't have to worry about the problem.
Section 1 text encoding and Unicode standards
To interpret Unicode strings, you must start with Unicode encoding. As we all know, text display has always been a basic problem that must be solved by the computer display function. Computers are not literate. they actually regard text as a string of "images", and each "image" corresponds to a character. When displaying text, each computer program must use a set of "images" that records how the text "images" is displayed to find the data corresponding to "Images" for each character, and draw the word "painting" to the screen based on the image. This "image" is called "font model", and the set of data displayed by the record model is called "character set ". For the convenience of searching, the data of each character model must be sorted in the character set, and each character is assigned a unique ID, which is the character encoding. During character data processing on a computer, this encoding always represents the character it represents. Therefore, a character set specifies the character data that a group of computers can process. Obviously, different countries specify different character sets with different sizes, and the corresponding character encoding is also different.
In computer history, the most widely used standardized character set is the first ASCII character set. It is actually a standard set in the United States and is developed for users in North America. It is encoded in seven binary digits and can contain 128 characters. This character set was finally officially accepted as an international standard by ISO and is widely used in various computer systems. Nowadays, all the PCs in the BIOS contain the ASCII character set.
However, when a computer is widely used in various countries, the limitations of ASCII encoding are exposed: its character space is limited and it cannot accommodate more characters, however, the vast majority of languages require more than 128 characters. In order to be able to correctly process Chinese characters, the official or private parties of various countries have begun to design their own text collections, and finally many character encodings have emerged for the texts of various countries, for example, for Western European characters ISO-8859-1 encoding, for simplified Chinese GB series encoding, as well as for Japanese SHIFT-JIS encoding and so on. At the same time, to ensure that each new character set is compatible with the original ASCII text, most character sets use the ASCII character as their first 128 characters, and make it one-to-one correspondence with the ASCII encoding.
In this way, the problem of text display in various countries is solved, but it brings about a new problem: Garbled code. Character sets used in different countries and regions are not subject to unified rules. Therefore, character sets are often not compatible with each other. The same character is generally encoded differently in two different character sets, while the same character is different in different character sets. A piece of text compiled by encoding A is often displayed as A pile of messy characters in A system that only supports encoding B. Even worse, different character sets often use different encoding lengths. when single-byte encoding-only programs encounter dual-byte or even multi-byte-encoded texts, it is often because it cannot be correctly processed that it produces the notorious "half a word" problem. This makes the already chaotic situation even more messy.
To solve these problems once and for all, many large companies and organizations in the industry have jointly proposed a standard, Unicode. Unicode is actually a new character encoding system. It encodes each character in the character set with an idnumber of two bytes to specify an encoding space that can contain up to 65536 characters, in addition, the commonly used words in the international coding industry are exhausted. Due to the comprehensive consideration in the design of the encoding, Unicode effectively solves the issue of garbled characters and "half characters" when other character sets are used for data communication. At the same time, the designers of Unicode fully consider the fact that a large amount of model data is still used by various countries, and put forward the design concept of "using Unicode as internal encoding. That is to say, the character display program still uses the original encoding and code, while the internal logic of the application uses Unicode. To display text, the program always converts Unicode-encoded strings to the original encoding for display. In this way, you do not have to re-design the data system of the model to use Unicode. At the same time, in order to be different from the encoding developed by countries, Unicode designers refer to Unicode as "wide characters encodings ), multi bypes encodings is also known as multi bypes encoding ). Today, the Unicode system has introduced four bytes of extended encoding, and gradually with the UCS-4, that is, iso000046 encoding specification convergence, hoping to one day with iso000046 system unified all the world's text encoding.
Since its birth, the Unicode system was highly expected and quickly accepted as an international standard recognized by ISO. However, Unicode was first opposed by European and American users during the promotion process. The reasons for their opposition are very simple: European and American users originally used single-byte encoding, and the dual-byte Unicode processing engine could not process the original single-byte data; if you want to convert all the existing single-byte text to Unicode, the workload will be too large. Besides, if all single-byte encoded texts are converted to double-byte Unicode encoding, the space occupied by all their text data will be twice the original space, in addition, all the processing programs must be rewritten. They cannot accept this overhead.
Although Unicode is an internationally recognized standard, it is impossible for the organization to ignore the requirements of the largest computer user group in Europe and America. So under the negotiation of the parties, a Unicode variant version was generated, which is the UTF-8. UTF-8 is a multi-byte encoding system, its encoding rules are as follows:
1. UTF-8 encoding is divided into four areas:
The first zone is single-byte encoding,
Encoding format: 0 xxxxxxx;
Unicode: 0x0000-0x007f
The second zone is dubyte encoding,
Encoding format: 110 xxxxx 10 xxxxxx;
Unicode: 0x0080-0x07ff
Three-byte encoding,
Encoding format: 1110 xxxx 10 xxxxxxx 10 xxxxxx
Unicode: 0x0800-0 xffff
The four-byte encoding,
The encoding format is 11110xxx 10 xxxxxxx 10 xxxxxx 10 xxxxxx.
Unicode: 0x00010000-0x0001ffff
Five-byte encoding,
The encoding format is 111110xx 10 xxxxxxx 10 xxxxxxx 10 xxxxxxx 10 xxxxxxx.
Unicode: 0x00200000-0x03ffffff
Zone 6 is a six-byte encoding,
The encoding format is 111110x 10 xxxxxxx 10 xxxxxxx 10 xxxxxxx 10 xxxxxxx
Unicode: 0x04000000-0x7fffffff
The first, second, and third areas correspond to the Unicode dubyte encoding area, while the four areas are extended to the four bytes of Unicode (according to this definition, the UTF-8 has five and six areas, but I did not find it in the GNU glibc library, I don't know why );
2. each area is arranged in ascending order of 1, 2, 3, 4, 5, and 6, and the characters at the corresponding position are the same as those at Unicode;
3. non-printable Unicode characters are encoded as 0 bytes, in other words, they are not included in the UTF-8 (this is the author's argument from the gnu c Library comment, may not match the actual situation );
According to the UTF-8 coding rules, it is not difficult to find that the 128 encoding in the first section is actually ASCII encoding. So the UTF-8 processing engine can directly process ASCII text. However, UTF-8's compatibility with ASCII encoding is at the cost of other encodings. For example, the original Chinese, Japanese, Korean words are basically double byte encoding, but their location in Unicode encoding corresponds to the three areas in the UTF-8, each character encoding must be three bytes long. In other words, if we convert all the existing non-ASCII character text data of the Chinese, Japanese, and Korean codes into UTF-8 encoding, the size will be 1.5 times the original.
Although I personally think that the UTF-8 encoding method is somewhat unfair, but it solves the problem of the transition from ASCII text to Unicode world after all, so it has won wide acceptance. Typical examples are XML and Java: the default encoding of XML text is UTF-8, and Java source code can actually be written with UTF-8 characters (JBuilder users should be impressed ). In addition, GTK 2.0, the world's famous open-source software, uses UTF-8 characters as internal encoding.
After talking so much, it seems that the topic is a little too far away. many Python enthusiasts may have started to worry: "What is the relationship between this and Python ?" Okay. now let's turn our eyes to the world of Python.
Section 2 Unicode encoding system of Python
To correctly process multilingual text, Python introduces Unicode strings after version 2.0. Since then, there have been two types of strings in the Python language: one is a traditional Python string that has been used for a long time before version 2.0, and the other is a new Unicode string. In Python, we use the unicode () built-in function to "decode" a traditional Python string, get a Unicode string, and then use the encode () of the Unicode string () this Unicode string is "encoded" and "encoded" into a traditional Python string. Therefore, every Python user must be familiar with it. But you know that the Unicode string of Python is not really a "Unicode-encoded string", but follows a unique rule. The content of this rule is very simple:
1. the Python Unicode encoding of ASCII characters is the same as their ASCII encoding.That is to say, the ASCII text in the Unicode string of Python is still a single-byte length encoding;
2. for characters other than ASCII characters, the encoding is double-byte (or four-byte) encoding of Unicode standard encoding. (I guess the reason why the Python community has to develop such an odd standard may be to ensure the universality of ASCII strings)
In Python applications, Unicode strings are used for internal processing, while Terminal Display is performed by traditional Python strings (in fact, the print statement of Python cannot print double-byte Unicode characters ). In Python, traditional Python strings are called "multi-byte encoding" strings, it is used to indicate various strings that are "encoded" into a specific character set encoding (such as GB, BIG5, KOI8-R, JIS, ISO-8859-1, of course there is also a UTF-8 ); the Python Unicode string is a "wide character encoding" string, indicating the Unicode data that is "Decoded" from a specific character set encoding. Therefore, a Python application that requires Unicode encoding usually processes string data as follows:
def foo(string, encoding = "gb2312"):# 1. convert multi-byte string to wide character stringu_string = unicode(string, encoding)# 2. do something...# 3. convert wide character string to printable multi-byte stringreturn u_string.encode(encoding)
We can give an example: Python that often uses PyGTK2 for XWindow programming in Red Hat Linux may have long known this situation: if we directly write the following statement:
Import pygtkpygtk. require ('2. 0') import gtkmain = gtk. Window () # create a windowmain. set_title ("Hello") # NOTICE!
When executing such a statement, the following warning will appear on the terminal:
Error converting from UTF-8 to 'gb18030': invalid character sequence in conversion input
In addition, the program window title will not be set to "Hello"; however, if the user installs a Chinese codec and changes the last sentence above:
U_string = unicode (' ', 'gb2312') main. set_title (u_string)
The program window title will be correctly set to "Hello ". Why?
The reason is simple. The gtk. Window. set_title () method always treats the title string you receive as a Unicode string. When the PyGTK system receives the user's main. set_title () request, it processes the resulting string somewhere as follows:
class Window(gtk.Widget):...def set_title(self, title_unicode_string):...# NOTICE! unicode -> multi-byte utf-8real_title_string = title_unicode_string.encode('utf-8')...# pass read_title_string to GTK2 C API to draw the title...
We can see that the string title_unicode_string is "encoded" into a new string in the program: real_title_string. Apparently, this real_title_string is a traditional Python string, and its encoding uses UTF-8. In the previous section, the author once mentioned that the internal use of GTK2 strings are encoded by UTF-8, so the GTK2 core system can correctly display the title after receiving real_title_string.
What if the title entered by the user is an ASCII string (for example, "hello world? Looking back at the definition rules of the Python Unicode string, it is not difficult to find that if the user input is an ASCII string, it will be re-encoded to get its own. That is to say, if the value of title_unicode_string is an ASCII string, the values of real_title_string and title_unicode_string will be exactly the same. And an ASCII string is a UTF-8 string, passing it to the GTK2 system will not have any problem.
The above example is about PyGTK2 in Linux, but similar problems not only occur in PyGTK. In addition to PyGTK, today's various graphical packages bound to Python, such as PyQT and Tkinter, are more or less prone to Unicode processing problems.
Now we have figured out the Unicode character string encoding mechanism of Python, but the problem we want to know most is not solved: how can we make Python support using Unicode to process Chinese characters? This issue will be explained in the next section.
Section 3 How to enable Unicode strings in Python to support Chinese characters
After reading the title of this section, some Python colleagues may disagree: "Why must Unicode be used to process Chinese characters? Isn't it good to use traditional Python strings ?" Indeed, in general, it is enough to use a traditional Python string for operations such as string connection and substring matching. However, if some advanced string operations are involved, such as regular expression matching, text editing, and expression analysis for multi-country texts, these operations that mix a large number of single-byte and multi-byte texts are very troublesome if they are processed using traditional strings. Besides, traditional strings cannot solve the "half a word" problem. If Unicode can be used, all these problems can be solved. Therefore, we must face up to and try to solve the problem of Chinese Unicode processing.
As described in the previous section, if you want to use the Unicode mechanism of Python to process strings, you only need to have a multi-byte Chinese encoding (including the GB encoding series and BIG5 series) and Unicode encoding for two-way conversion of the encoding/decoding module. In Python terms, such an encoding/decoding module is called codec. Then the question becomes: how do we compile such a codec?
If the Unicode mechanism of Python is hard-coded in the core of Python, adding a new codec to Python will be a tough task. Fortunately, Python designers are not so stupid. they provide an excellent scalability mechanism to easily add new codecs for Python.
The Python Unicode processing module has three most important components: the codecs. py file, the encodings directory, and the aliases. py file. Both are located in the installation directory of the Python system Library (for Win32 release, it is in the $ PYTHON_HOME/lib/directory; for Red Hat Linux, in the/usr/lib/python-version/directory, other systems can look for it here), and the last one is in the encodings directory. Next, we will describe the three.
Let's take a look at the codecs. py file. This file defines the interface that a standard Codec module should have. The specific content can be found in your Python release and will not be described here. According to the definition of the codecs. py file, a complete codec should have at least three classes and a standard function:
1. Codec class
Purpose:
The buffer data (a buffer) passed by the user is used as a traditional Python string, and
It is decoded as the corresponding Unicode string. A complete Codec class definition must provide Codec. decode () and
Codec. encode () two methods:
Codec.decode(input, errors = "strict")
It is used to treat the input data as a traditional Python string and "decodes" it into a corresponding Unicode string.
Parameters:
Input: the input buffer (which can be a string or any object that can be converted to a string)
Errors: the processing option when a conversion error occurs. You can select the following three values:
Strict (default): If an error occurs, a UnicodeError exception is thrown;
Replace: if an error occurs, replace it with a default Unicode code;
Ignore: if an error occurs, ignore this character and analyze the remaining characters.
Return value:
A constant list (tuple): The first element is the converted Unicode string, and the last element is the length of the input data.
Codec.encode(input, errors = "strict")
It is used to treat the input data as a Unicode string and "encode" it into a corresponding traditional Python string.
Parameters:
Input: input buffer (usually a Unicode string)
Errors: the processing option when a conversion error occurs. The value rules are the same as those of Codec. decode.
Return value:
A constant list (tuple): The first element is the converted traditional Python string, and the last element is the length of the input data.
2. StreamReader class (generally inherited from Codec class)
Used to analyze the file input stream. Provides all read operations on file objects, such as the readline () method.
3. StreamWriter class (generally inherited from Codec class)
Used to analyze the file output stream. Provides all write operations on file objects, such as the writeline () method.
5. getregentry () function
That is, "GET REGistry ENTRY" is used to obtain the four key functions defined in each Codec file. The functions are as follows:
def getregentry():return tuple(Codec().encode,Codec().decode,StreamReader,StreamWriter)
In all the four classes mentioned above, only the Codec class and the getregentry () function are required. The former must be provided because it is a module that actually provides conversion operations, while the latter is a standard interface that the Python system obtains the Codec definition, so it must exist. As for StreamReader and StreamWriter, theoretically, you can inherit the StreamReader and StreamWriter classes in codecs. py and use their default implementations. Of course, many codec rewrite these two classes to implement some special customization functions.
Next let's talk about the encodings directory. As the name suggests, the encodings directory is the place where the Python system stores all installed codec by default. Here we can find all the built-in codecs of the Python release. Traditionally, every new codec will install itself here. Note that the Python system does not require all codec to be installed here. You can place the new codec in any position you like, as long as the search path of the Python system can be found.
It is not enough to install your own codec in the path that Python can find. To enable the Python system to find the corresponding codec, you must register it in Python. To register a new codec, you must use the aliases. py file under the encodings directory. This file only defines a hash table aliases. each of its keys corresponds to the name of each codec in use, that is, the second parameter value of the unicode () built-in function; the value corresponding to each key is a string, which is the module name of the processing file corresponding to the codec. For example, Python's default parsing UTF-8 codec is utf_8.py, which is stored in the encodings subdirectory, then the aliases hash table has a corresponding relationship:
'utf-8' : 'utf_8', # the module `utf_8' is the codec for UTF-8
Similarly, if we write a new codec that parses the 'mycharset' character set, assume that the encoding file is mycodec. py, which is stored in the $ PYTHON_HOME/lib/site-packages/mycharset/Directory. then we must add this line to the aliases hash table:
'mycharset' : 'mycharset.mycodec',
The full path name of mycodec. py does not need to be written here, because the site-packages directory is usually in the search path of the Python system.
The aliases. py file under the encodings directory is automatically loaded when the Python interpreter needs to analyze the Unicode string. If mycharset has been registered in the system, we can use our own codec as we use other built-in encoding. For example, if mycodec. py is registered as follows, we can write it as follows:
my_unicode_string = unicode(a_multi_byte_string, 'mycharset')print my_unicode_string.encode('mycharset')
Now we can summarize the steps required to write a new codec:
First, we need to write our own codec encoding/decoding module;
Second, we need to put this module file in a place that can be found by a Python interpreter;
Finally, we need to register it in the encodings/aliases. py file.
Theoretically, with these three steps, we can install our codec into the system. However, there is still a small problem. Sometimes, we do not want to modify our system files for various reasons (for example, if a user is working in a centralized system, the system administrator cannot allow others to modify the system files ). In the above steps, we need to modify the content of the aliases. py file, which is a system file. But if we cannot modify it, can we not add a new codec? No, of course we have a solution.
This method is to modify the content of the encodings. aliases. aliases hash table at runtime.
Use the above assumption. if the administrator of the user's work system does not allow the user to write the registration information of mycodec. py into aliases. py, we can do this:
1. put mycodec. py in a directory, such as the/home/myname/mycharset/directory;
2. write the/home/myname/mycharset/init. py file as follows:
import encodings.aliases# update aliases hash mapencodings.aliases.aliases.update({/'mycodec' : 'mycharset.mycodec',/}}
To use Python in the future, we can add/home/myname/to the search path and execute it in advance when using our own codec:
import mycharset # execute the script in mycharset/init.py
In this way, we can use the new codecs without modifying the original system file. In addition, with the help of the Python site mechanism, we can also automate the import work. If you do not know what site is, run the following command in your Python interaction environment:
import siteprint site.doc
View the documentation of the site module to understand the skills. If you have Red Hat Linux v8 and v9 on hand, you can also refer to the Japanese codec included in the Red Hat Python release to see how it achieves automatic loading. Some of them may not be able to find the location of the Japanese codec, which is listed as follows:
Red Hat Linux v8: Under the/usr/lib/python2.2/site-package/japanese/directory; Red Hat Linux v9: in the/usr/lib/python2.2/lib-dynload/japanese/directory;
Tip: Red Hat users should pay attention to the japanese. pth file under the site-packages directory. combined with the documentation of the site module, I believe it will be clear immediately.
Conclusion
I remember that at the beginning, I spoke to Haikou on the Dohao Forum: "If you can, I can write a (Chinese module) for everyone." In retrospect, I can't help but feel ashamed of myself. I spent all my time studying. I learned only seven courses a semester and got a dumb graduate who failed two courses, where are the qualifications so arrogant. Now, the burden on the two courses has increased sharply in the second semester (ten courses !), In the family, the old father and mother are still waiting for their sons to make faces for them. To ensure both learning and work within a limited period of time (I want to undertake the tutor's course tutoring work, and I need to pick up a major plan for teaching reform in a school ), I am exhausted, and I am adding a Chinese module ...... Alas, please forgive me for lack of skills, and I have to break into your words.
Therefore, I am so bold that I am here to share my experiences over the past six months. I only hope that I can find a batch of people who are interested in this project, even one, I can take the knowledge I have already compiled and compile a complete (at least GB, BIG5, I personally think, or even HZ code) Chinese module, contributing to everyone (whether paid or free) is a blessing for the majority of Python enthusiasts. In addition, the Python release has not yet included any Chinese support modules. Since I love Python on a daily basis, if we can make some contributions to the development of Python, why not?
Appendix: Tips
1. LUO jian.pdf has compiled a very incorrect Chinese character (the file name is showfile.zip, which is much faster than the draft version I have written) and supports GB2312 and GB18030 encoding. Unfortunately, BIG5 is not supported. If you are interested, you can download this module for research;
2. compared with other character set encoding, the Chinese module has its own particularity, that is, its massive number of characters. Some relatively small character sets, such as GB2312, can be searched using a hash table. For the huge GB18030 encoding, if we simply make all the data into a super large encoding table, the query speed is too slow to be tolerated (this is the biggest headache for the author in writing the module ). If you want to write a codec with satisfactory speed, you must consider designing a formula to calculate another one from one encoding by simple computation, or at least, we can calculate its approximate range. This requires the programmer to make statistics on the entire encoding scheme and try to find the rule. The author believes that this should be the biggest difficulty in writing Chinese modules. It may be because the mathematical skills are too poor, and I am not able to find a rule with all my efforts. Hope you can have a good math;
3. the Chinese encoding is divided into two main factions: GB and BIG5. Among them, GB is divided into GB2312, GBK and GB18030 three encoding, while BIG5 is also divided into BIG5 and BIG5-HKSCS two (corresponding to the original BIG5 and Hong Kong extension version ). Although the codes of the same faction can be backward compatible, considering the large number of characters, it is reasonable to separate them for faster search. Of course, if the conversion formula of the corresponding character set can be found, this separation is unnecessary;
The above is a detailed explanation of the Unicode and Python Chinese processing methods. For more information, see other related articles in the first PHP community!