Implementation method of detecting rare words in Python
Solution ideas
The first thing that comes to mind is to use python’s regular expressions to match illegal characters and then find illegal records. However, ideals are always full, but reality is cruel. During the implementation process, I discovered that I lacked knowledge about character encoding and Python's internal string representation. During this period, I went through a lot of pitfalls, and although there were still some ambiguities in the end, I finally had an overall clear understanding. Record your experience here to avoid falling in the same place in the future.
The following test environment is the python 2.7.8 environment that comes with ArcGIS 10.3. There is no guarantee that other python environments will also be suitable.
python regular expression
The regular function in python is provided by the built-in re function library, which mainly uses 3 functions. re.compile()
Provides reusable regular expressions, match()
and search()
functions return matching results. The difference between the two is: match()
starts matching from the specified position, search()
will search backward from the specified position until a matching string is found. For example, in the code below, match_result
starts matching from the first character f, and returns a null value if the match fails; search_result
searches backward from f until it finds the first matching character a, and then uses the group() function The output matching result is the character a.
import re pattern = re.compile('[abc]') match_result = pattern.match('fabc') if match_result: print match_result.group() search_result = pattern.search('fabc') if search_result: print search_result.group()
The above implementation requires compiling a pattern first and then matching. In fact, we can directly use the re.match(pattern, string)
function to achieve the same function. However, the direct matching method is not as flexible as compiling first and then matching. First of all, regular expressions cannot be reused. If a large amount of data is matched with the same pattern, it means that internal compilation is required every time, resulting in performance loss; in addition, re.match The ()
function is not as powerful as pattern.match()
, which can specify the position from which to start matching.
Encoding problem
After understanding the basic functions of python regular expressions, the only thing left is to find a suitable regular expression to match rare words and illegal characters. Illegal characters are very simple and can be matched using the following pattern:
pattern = re.compile(r'[~!@#$%^&* ]')
However, the matching of rare characters really stumped me. The first is the definition of rare words. What kind of words are considered rare? After consultation with the project manager, it was determined that non-GB2312 characters are rare characters. The next question is, how to match GB2312 characters?
After inquiry, the range of GB2312 is [xA1-xF7][xA1-xFE]
, among which the range of Chinese character area is [xB0-xF7][xA1-xFE]
. Therefore, the expression after adding rare word matching is:
pattern = re.compile(r'[~!@#$%^&* ]|[^\xA1-\xF7][^\xA1-\xFE]')
The problem seems to be solved smoothly, but I am still too simple and too naive. Since the strings to be judged are all read from layer files, arcpy thoughtfully encodes the read characters into unicode format. Therefore, I need to find out the encoding range of GB2312 character set in unicode. But the reality is that the distribution of the GB2312 character set in unicode is not continuous, and using regular expressions to represent this range must be very complicated. The idea of using regular expressions to match rare words seems to have hit a dead end.
Solution
Since the provided string is in unicode format, can I convert it to GB2312 and then match it? In fact, it is not possible, because the unicode character set is much larger than the GB2312 character set, so GB2312 => unicode
can always be achieved, but conversely unicode => GB2312
may not necessarily succeed.
This suddenly provided me with another idea. Assuming that the unicode => GB2312
conversion of a string will fail, does that mean that it does not belong to the GB2312 character set? So, I use the unicode_string.encode('GB2312')
function to try to convert the string and catch the UnicodeEncodeError exception to identify the rare characters.
The final code is as follows:
import re def is_rare_name(string): pattern = re.compile(u"[~!@#$%^&* ]") match = pattern.search(string) if match: return True try: string.encode("gb2312") except UnicodeEncodeError: return True return False
Summary
The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

When installing PyTorch on CentOS system, you need to carefully select the appropriate version and consider the following key factors: 1. System environment compatibility: Operating system: It is recommended to use CentOS7 or higher. CUDA and cuDNN:PyTorch version and CUDA version are closely related. For example, PyTorch1.9.0 requires CUDA11.1, while PyTorch2.0.1 requires CUDA11.3. The cuDNN version must also match the CUDA version. Before selecting the PyTorch version, be sure to confirm that compatible CUDA and cuDNN versions have been installed. Python version: PyTorch official branch

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.
