Python file Content parsing (1)

Source: Internet
Author: User
Tags ming

Description

  There is a file joke.txt, which reads as follows:

Teacher: The choppy radicals are three points of water. Ming Li A similar example:
Xiao Ming: Pie wonton?
Teacher: Let's change one.
Xiao Ming: Play glass ball.
Teacher: Not good.
Xiao ming:... Can't bathe?
Teacher: Have the ability to have a six word?
Xiao Ming: Oh, MI-mi-coax.
Teacher: a 100-word!
Xiao Ming: haha haha haha ...
Teacher: Get outta here!!!

Output it in the following way:

The teacher said : The choppy radicals are three points of water. Ming Li A similar example:
Xiao Ming said: Pie wonton?
The teacher said, "Let's change one."
Xiao Ming said: Play glass ball.
The teacher said: "Not good."
Xiao Ming said: ... Can't bathe?
The teacher said: "Have the ability to a six words?"
Xiao Ming said, "Oh, MI-mi-Coax."
The teacher said: "To a 100 words!"
Xiao Ming said: haha haha haha ...
Teacher said: Get out!!!

The code is as follows:

Import OS # importing System Libraries

Try
data = open (' Joke.txt ') # opening file
Data.seek (0) # Navigate to file start location

For each_line in data:
Try:
(role, word) = Each_line.split (': ', 1) # Parse the data, the parameter ' 1 ' in Split means only the first ': ' Is parsed
print (role, end= ') # prints in the new format, which can also be added to the list
print (' Say: ', end= ')
print (Word, end= ")
except ValueError: # exception handling
print ('------valueerror occur! ')

Except IOError:
Print ('---The file is missing. ')
Finally
Data.close () # Close File

Python file Content parsing (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.