Python3.5 learning notes -- use a dictionary to replace a specified text string,
The reason is that a colleague needs to replace the content of a column in batches after organizing the excel file.
Example:
Data format: The following is a column of content. Each row is in a cell. The purpose is to replace the number with a specified Chinese character.
1, 2, 31
, 4, 33
, 21 ,,
After thinking about the solution, I think shell can be used, but it may be relatively troublesome,
When using a database, the efficiency is too low because the data is in a cell.
Finally, I think this is exactly the application of the dictionary in python3.5. I wrote a script to implement it. The specific script is as follows:
1. paste a column to be processed and replace multiple commas with spaces to convert the list.
######################################## ###############
# Encoding: UTF-8
A_dict = {1: 'hello', 2: 'Hi loan', 3: 'Hello loan '}
Input_file = open (r 'C: \ Users \ xxxx \ Desktop \ shuju \ shuju.txt ', 'R') # read Source File
Output_file = open (r 'C: \ Users \ xxxx \ Desktop \ shuju \ result.txt ', 'a +') # append the data to the result file.
Line = input_file.readline ()
While line: # Read source files row by row
A = line. split () # convert each row to a list-list
Res = [] # create a result list
For item in:
Res. append (a_dict [int (item)]) # Write the result to the result list.
Output_file.write (str (res) + '\ n') # append the result list to the result file.
Line = input_file.readline ()
Input_file.close () # close the file
Output_file.close ()
######################################## ###################################
In fact, this is not a replacement in the true sense, and the replace () method is not used.
When I tried the replace () method, I found that he could not read the numbers in the text well and could not process the double digits.
Therefore, the logic may be clearer for me to directly convert the target and re-output it.