Dive Into Python-Chapter 7. Regular Expressions
Số trang: 23
Loại file: pdf
Dung lượng: 0.00 B
Lượt xem: 9
Lượt tải: 0
Xem trước 3 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
Tham khảo tài liệu dive into python-chapter 7. regular expressions, công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả
Nội dung trích xuất từ tài liệu:
Dive Into Python-Chapter 7. Regular Expressions Chapter 7. Regular ExpressionsRegular expressions are a powerful and standardized way of searching,replacing, and parsing text with complex patterns of characters. If youveused regular expressions in other languages (like Perl), the syntax will bevery familiar, and you get by just reading the summary of the re module toget an overview of the available functions and their arguments.7.1. Diving InStrings have methods for searching (index, find, and count), replacing(replace), and parsing (split), but they are limited to the simplest ofcases. The search methods look for a single, hard-coded substring, and theyare always case-sensitive. To do case-insensitive searches of a string s, youmust call s.lower() or s.upper() and make sure your search stringsare the appropriate case to match. The replace and split methods havethe same limitations.If what youre trying to do can be accomplished with string functions, youshould use them. Theyre fast and simple and easy to read, and theres a lot tobe said for fast, simple, readable code. But if you find yourself using a lot ofdifferent string functions with if statements to handle special cases, or ifyoure combining them with split and join and list comprehensions inweird unreadable ways, you may need to move up to regular expressions.Although the regular expression syntax is tight and unlike normal code, theresult can end up being more readable than a hand-rolled solution that uses along chain of string functions. There are even ways of embedding commentswithin regular expressions to make them practically self-documenting.7.2. Case Study: Street AddressesThis series of examples was inspired by a real-life problem I had in my dayjob several years ago, when I needed to scrub and standardize streetaddresses exported from a legacy system before importing them into a newersystem. (See, I dont just make this stuff up; its actually useful.) Thisexample shows how I approached the problem.Example 7.1. Matching at the End of a String>>> s = 100 NORTH MAIN ROAD>>> s.replace(ROAD, RD.)100 NORTH MAIN RD.>>> s = 100 NORTH BROAD ROAD>>> s.replace(ROAD, RD.)100 NORTH BRD. RD.>>> s[:-4] + s[-4:].replace(ROAD, RD.)100 NORTH BROAD RD.>>> import re>>> re.sub(ROAD$, RD., s)100 NORTH BROAD RD. My goal is to standardize a street address so that ROAD is always abbreviated as RD.. At first glance, I thought this was simple enough that I could just use the string method replace. After all, all the data was already uppercase, so case mismatches would not be a problem. And the search string, ROAD, was a constant. And in this deceptively simple example, s.replace does indeed work. Life, unfortunately, is full of counterexamples, and I quickly discovered this one. The problem here is that ROAD appears twice in the address, once as part of the street name BROAD and once as its own word. The replace method sees these two occurrences and blindly replaces both of them; meanwhile, I see my addresses getting destroyed. To solve the problem of addresses with more than one ROAD substring, you could resort to something like this: only search and replace ROAD in the last four characters of the address (s[-4:]), and leave the string alone (s[:-4]). But you can see that this is already getting unwieldy. For example, the pattern is dependent on the length of the string youre replacing (if you were replacing STREET with ST., you would need to use s[:-6] and s[-6:].replace(...)). Would you like to come back in six months and debug this? I know I wouldnt. Its time to move up to regular expressions. In Python, all functionality related to regular expressions is contained in the re module. Take a look at the first parameter: ROAD$. This is a simple regular expression that matches ROAD only when it occurs at the end of a string. The $ means “end of the string”. (There is a corresponding character, the caret ^, which means “beginning of the string”.) Using the re.sub function, you search the string s for the regular expression ROAD$ and replace it with RD.. This matches the ROAD at the end of the string s, but does not match the ROAD thats part of the word BROAD, because thats in the middle of s.Continuing with my story of scrubbing addresses, I soon discovered that theprevious example, matching ROAD at the end of the address, was notgood enough, because not all addresses included a street designation at all;some just ended with the street name. Most of the time, I got away with it,but if the street name was BROAD, then the regular expression wouldmatch ROAD at the end of the string as part of the word BROAD, whichis not what I wanted.Example 7.2. Matching Whole Words>>> s = 100 BROAD>>> r ...
Nội dung trích xuất từ tài liệu:
Dive Into Python-Chapter 7. Regular Expressions Chapter 7. Regular ExpressionsRegular expressions are a powerful and standardized way of searching,replacing, and parsing text with complex patterns of characters. If youveused regular expressions in other languages (like Perl), the syntax will bevery familiar, and you get by just reading the summary of the re module toget an overview of the available functions and their arguments.7.1. Diving InStrings have methods for searching (index, find, and count), replacing(replace), and parsing (split), but they are limited to the simplest ofcases. The search methods look for a single, hard-coded substring, and theyare always case-sensitive. To do case-insensitive searches of a string s, youmust call s.lower() or s.upper() and make sure your search stringsare the appropriate case to match. The replace and split methods havethe same limitations.If what youre trying to do can be accomplished with string functions, youshould use them. Theyre fast and simple and easy to read, and theres a lot tobe said for fast, simple, readable code. But if you find yourself using a lot ofdifferent string functions with if statements to handle special cases, or ifyoure combining them with split and join and list comprehensions inweird unreadable ways, you may need to move up to regular expressions.Although the regular expression syntax is tight and unlike normal code, theresult can end up being more readable than a hand-rolled solution that uses along chain of string functions. There are even ways of embedding commentswithin regular expressions to make them practically self-documenting.7.2. Case Study: Street AddressesThis series of examples was inspired by a real-life problem I had in my dayjob several years ago, when I needed to scrub and standardize streetaddresses exported from a legacy system before importing them into a newersystem. (See, I dont just make this stuff up; its actually useful.) Thisexample shows how I approached the problem.Example 7.1. Matching at the End of a String>>> s = 100 NORTH MAIN ROAD>>> s.replace(ROAD, RD.)100 NORTH MAIN RD.>>> s = 100 NORTH BROAD ROAD>>> s.replace(ROAD, RD.)100 NORTH BRD. RD.>>> s[:-4] + s[-4:].replace(ROAD, RD.)100 NORTH BROAD RD.>>> import re>>> re.sub(ROAD$, RD., s)100 NORTH BROAD RD. My goal is to standardize a street address so that ROAD is always abbreviated as RD.. At first glance, I thought this was simple enough that I could just use the string method replace. After all, all the data was already uppercase, so case mismatches would not be a problem. And the search string, ROAD, was a constant. And in this deceptively simple example, s.replace does indeed work. Life, unfortunately, is full of counterexamples, and I quickly discovered this one. The problem here is that ROAD appears twice in the address, once as part of the street name BROAD and once as its own word. The replace method sees these two occurrences and blindly replaces both of them; meanwhile, I see my addresses getting destroyed. To solve the problem of addresses with more than one ROAD substring, you could resort to something like this: only search and replace ROAD in the last four characters of the address (s[-4:]), and leave the string alone (s[:-4]). But you can see that this is already getting unwieldy. For example, the pattern is dependent on the length of the string youre replacing (if you were replacing STREET with ST., you would need to use s[:-6] and s[-6:].replace(...)). Would you like to come back in six months and debug this? I know I wouldnt. Its time to move up to regular expressions. In Python, all functionality related to regular expressions is contained in the re module. Take a look at the first parameter: ROAD$. This is a simple regular expression that matches ROAD only when it occurs at the end of a string. The $ means “end of the string”. (There is a corresponding character, the caret ^, which means “beginning of the string”.) Using the re.sub function, you search the string s for the regular expression ROAD$ and replace it with RD.. This matches the ROAD at the end of the string s, but does not match the ROAD thats part of the word BROAD, because thats in the middle of s.Continuing with my story of scrubbing addresses, I soon discovered that theprevious example, matching ROAD at the end of the address, was notgood enough, because not all addresses included a street designation at all;some just ended with the street name. Most of the time, I got away with it,but if the street name was BROAD, then the regular expression wouldmatch ROAD at the end of the string as part of the word BROAD, whichis not what I wanted.Example 7.2. Matching Whole Words>>> s = 100 BROAD>>> r ...
Tìm kiếm theo từ khóa liên quan:
thủ thuật máy tính công nghệ thông tin quản trị mạng tin học computer networkTài liệu liên quan:
-
52 trang 434 1 0
-
24 trang 359 1 0
-
Top 10 mẹo 'đơn giản nhưng hữu ích' trong nhiếp ảnh
11 trang 321 0 0 -
Làm việc với Read Only Domain Controllers
20 trang 312 0 0 -
74 trang 304 0 0
-
96 trang 299 0 0
-
Báo cáo thực tập thực tế: Nghiên cứu và xây dựng website bằng Wordpress
24 trang 292 0 0 -
Đồ án tốt nghiệp: Xây dựng ứng dụng di động android quản lý khách hàng cắt tóc
81 trang 286 0 0 -
EBay - Internet và câu chuyện thần kỳ: Phần 1
143 trang 277 0 0 -
Tài liệu hướng dẫn sử dụng thư điện tử tài nguyên và môi trường
72 trang 270 0 0