This article mainly describes the Python implementation of simple text string processing methods, involving Python for text string cutting, calculation, conversion and other related operations skills, the need for friends can refer to the following
The examples in this article describe how Python implements simple text string processing. Share to everyone for your reference, as follows:
For a text string, you can use the Python string.split() method to cut it. Let's look at the actual running effect.
Mysent = ' This book was the best book on python! ' Print Mysent.split ()
Output:
[' This ', ' book ', ' was ', ' the ', ' best ', ' book ', ' On ', ' python! ']
As you can see, segmentation works fine, but punctuation is also used as a word and can be handled using regular expressions, where separators are any string except words and numbers.
Import Rereg = Re.compile (' \\w* ') mysent = ' This was the best book on python! ' Listof = Reg.split (mysent) Print Listof
The output is:
[' This ', ' book ', ' was ', ' the ', ' best ', ' book ', ' on ', ' Python ', ']
Now you get a list of words, but the empty strings inside are removed.
You can calculate the length of each string, returning only strings that are greater than 0.
Import Rereg = Re.compile (' \\w* ') mysent = ' This was the best book on python! ' Listof = Reg.split (mysent) new_list = [Tok for Tok in Listof if Len (tok) >0]print new_list
The output is:
[' This ', ' book ', ' was ', ' the ', ' best ', ' book ', ' on ', ' Python ']
Finally, the first letter in the sentence is found to be capitalized. We need the same form to convert uppercase to lowercase. Python-embedded method to convert all strings to lowercase ( .lower() ) or uppercase ( .upper() )
Import Rereg = Re.compile (' \\w* ') mysent = ' This was the best book on python! ' Listof = Reg.split (mysent) new_list = [Tok.lower () for Tok in Listof if Len (tok) >0]print new_list
The output is:
[' This ', ' book ', ' was ', ' the ', ' best ', ' book ', ' on ', ' Python ']
Let's look at a complete email:
Content
Hi Peter,with Jose out of town, does you want tomeet once in a while to keep thingsgoing and do some interesting stuff? Let me Knoweugene
Import Rereg = Re.compile (' \\w* ') email = open (' Email.txt '). Read () List = reg.split (email) new_txt = [Tok.lower () for Tok in List if Len (tok) >0]print New_txt
Output:
Copy the Code code as follows:
[' Hi ', ' Peter ', ' with ', ' Jose ', ' off ', ' of ', ' town ', ' do ', ' I ', ' want ', ' to ', ' meet ', ' once ', ' in ', ' a ', ' and ', ' to ', ' Keep ', ' things ', ' going ', ' and ', ' do ', ' some ', ' interesting ', ' stuff ', ' let ', ' me ', ' Know ', ' Eugene '
Related recommendations:
Python implements the method of obtaining the first 100 sets of tick counts