##A task
_Task: Split the data in the file (record.txt) and save it according to the following rules:
Keep the conversation as a separate boy_.txt file (remove "Little Turtle:")
Keep the conversation as a separate file for girl_.txt (remove "Little Customer Service:")
() - There are three conversations in the file, saved as boy_1.txt, girl_1.txt, boy_2.txt, girl_2.txt, boy_3.txt, gril_3.txt and 6 files (hint: different conversations in the file have been split with "=============")
Small customer service: Little turtle, today a customer asked you if you have a girlfriend? Little Turtle: Huh?? Small customer service: I told her you have a girlfriend! Little Turtle:...... Little Customer Service: She asked you to think about her after you broke up!Then I said, "If you want to buy a disc, I'll keep an eye on it." Little Turtle: And then? Small Customer Service: She bought two and said it would be good to ship one ~ Little Turtle: Uh..........You're really something! Small customer service: That's who made me the cutest little customer service of Fish C? Little Turtle: Next time someone wants to play tricks on you, I won't stop it~ Small customer service: Roll!!! ================================================================================ Small customer service: Little turtle, there is a good review very funny. Little Turtle: Oh? Little Customer Service: "With the little turtle, my mother will never have to worry about my study again." Little Turtle: Ha-ha, I see Yam, I also sent a microblog ~ Customer Service: Well, I saw your microblog ~ Little Turtle: Yoshi~ Little Customer Service: The reply reads, "Small turtle in left hand, lighter in right hand, where can't point anywhere, so easy ^^" Little Turtle: T_T ================================================================================ Small Customer Service: Little Turtle, a member is looking for you today Little Turtle: Oh?Yes? Little Customer Service: He said that your monthly salary for a student has exceeded 12k!! Little Turtle: Where? Small customer service: Shanghai Little Turtle: That's normal. Which company? Little customer service: He didn't say anything. Little Turtle: Oh Small customer service: Boss, why am I paid so low?It's time to get a raise!! Little Turtle: Ah, what did you say?I'm outside. It's noisy here. Small customer service: Roll!!!
f = open('record.txt') #First open the target file by default boy = [] #Store the little turtle girl = [] #Store customer service words count = 1 #Record the conversation for each_line in f: #Get one row at a time if each_line[:6] != '======': #Judges whether the line obtained is equal to the equal sign,Prefetch6Better judgements (role, line_spoken) = each_line.split(':', 1) #Let's split the string here,Separate front and back parts with colons if role == 'Little Turtle': boy.append(line_spoken) if role == 'Small customer service': girl.append(line_spoken) else: file_name_boy = 'boy_' + str(count) + '.txt' file_name_girl = 'girl_' + str(count) + '.txt' boy_file = open(file_name_boy, 'w') girl_file = open(file_name_girl, 'w') boy_file.writelines(boy) girl_file.writelines(girl) boy_file.close() girl_file.close() boy = [] girl = [] count += 1 file_name_boy = 'boy_' + str(count) + '.txt' file_name_girl = 'girl_' + str(count) + '.txt' boy_file = open(file_name_boy, 'w') girl_file = open(file_name_girl, 'w') boy_file.writelines(boy) girl_file.writelines(girl) boy_file.close() girl_file.close() f.close()
(When optimized with functions, you encapsulate code that is highly repetitive and then call it)
def save_file(boy, girl, count): file_name_boy = 'boy_' + str(count) + '.txt' file_name_girl = 'girl_' + str(count) + '.txt' boy_file = open(file_name_boy, 'w') girl_file = open(file_name_girl, 'w') boy_file.writelines(boy) girl_file.writelines(girl) boy_file.close() girl_file.close() def split_file(file_name): f = open('record.txt') boy = [] girl = [] count = 1 for each_line in f: if each_line[:6] != '======': (role, line_spoken) = each_line.split(':', 1) if role == 'Little Turtle': boy.append(line_spoken) if role == 'Small customer service': girl.append(line_spoken) else: save_file(boy, girl, count) boy = [] girl = [] count += 1 save_file(boy, girl, count) f.close() split_file('record.txt')
##Get started
0. Write a program that accepts user input and saves it as a new file, as shown in the diagram:
Answer:
Beginning tomorrow, be a happy person Feeding Horses, Chopping Wood, Traveling the World From tomorrow on, care about food and vegetables I have a house facing the sea with spring blossoms Communicate with every loved one from tomorrow Tell them my happiness What the lightening of happiness has told me I'll tell everyone Give each river a warm name to every mountain Stranger, I wish you well too May you have a brilliant future May your Valentine be a family May you enjoy happiness in this earthly world I just want to face the sea, spring blossom
def file_write(file_name): f = open(file_name, 'w') print('Please Enter Content [Enter Individually\':w\'Save Exit):') while True: write_some = input() if write_some != ':w': f.write('%s\n' % write_some) else: break f.close() file_name = input('Please enter a file name:') file_write(file_name)
1. Write a program that compares two files entered by the user and displays all the line numbers and the position of the first different character if they are different. The program implementation is shown in the following figure:
Answer:
def file_compare(file1, file2): f1 = open(file1) f2 = open(file2) count = 0 # Count rows differ = [] # Number of differences in Statistics for line1 in f1: line2 = f2.readline() count += 1 if line1 != line2: differ.append(count) f1.close() f2.close() return differ file1 = input('Enter the first file name to compare:') file2 = input('Please enter another file name to compare:') differ = file_compare(file1, file2) if len(differ) == 0: print('The two files are identical!') else: print('There are two files in common [%d]Where different:' % len(differ)) for each in differ: print('No. %d Lines are different' % each)
2. Write a program that prints the first N lines of the file to the screen when the user enters the file name and number of lines (N). The program is as follows:
Answer:
def file_view(file_name, line_num): print('\n file%s Before%s The contents are as follows:\n' % (file_name, line_num)) f = open(file_name) for i in range(int(line_num)): print(f.readline(), end= '') f.close() file_name = input(r'Please enter a file to open ( C:\\test.txt): ') line_num = input('Enter the first few lines of the file you want to display:') file_view(file_name, line_num)
3. Uh, we have to say that our users are getting more and more tricky.Requires that you expand on the previous question so that users can enter as many rows as they want to display.
(e.g. input 13:21 to print lines 13 to 21, input 21 to print the first 21 lines, input 21 to print everything from line 21 to the end of the file)
Answer:
def file_view(file_name, line_num): if line_num.strip() == ':': begin = '1' end = '-1' (begin, end) = line_num.split(':') if begin == '': begin = '1' if end == '': end = '-1' if begin == '1' and end == '-1': prompt = 'Full text' elif begin == '1': prompt = 'From start to%s' % end elif end == '-1': prompt = 'from%s To the end' % begin else: prompt = 'From%s Row to%s That's ok' % (begin, end) print('\n file%s%s The contents are as follows:\n' % (file_name, prompt)) begin = int(begin) - 1 end = int(end) lines = end - begin f = open(file_name) for i in range(begin): # Used to consume content before begin f.readline() if lines < 0: print(f.read()) else: for j in range(lines): print(f.readline(), end='') f.close() file_name = input(r'Please enter a file to open ( C:\\test.txt): ') line_num = input('Please enter the number of lines to display [format like 13]:21 or :21 Or 21: or : ]: ') file_view(file_name, line_num)
4. Write a program to implement the Replace All function as shown in the figure:
Answer:
def file_replace(file_name, rep_word, new_word): f_read = open(file_name) content = [] count = 0 for eachline in f_read: if rep_word in eachline: count = eachline.count(rep_word) #count feels it should use this eachline = eachline.replace(rep_word, new_word) content.append(eachline) decide = input('\n file %s Common in%s Each [%s]\n You're sure you want all of them%s]Replace with [%s]Are you?\n[YES/NO]: ' \ % (file_name, count, rep_word, rep_word, new_word)) if decide in ['YES', 'Yes', 'yes']: f_write = open(file_name, 'w') f_write.writelines(content) f_write.close() f_read.close() file_name = input('Please enter a file name:') rep_word = input('Enter the words or characters you want to replace:') new_word = input('Please enter a new word or character:') file_replace(file_name, rep_word, new_word)