In Python3: split
>>> Help (Each_line.split) Help on
built-in function split:
split (...) method of Builtins.str instance< C3/>s.split (Sep=none, maxsplit=-1)-> List of strings return
a list of the words in S, using Sep as the delimiter s Tring. If Maxsplit is given, at most maxsplit splits do. If Sep is not specified or are None, any whitespace string is a separator and empty strings are removed.
That is: Returns a list with Sep as the separator to S. If the maxsplit has been specified, at least a few pieces have been set. If Sep is not specified or none, then all spaces are delimiters, and empty strings are removed from the results. Strip
>>> Help (Line_spoken.strip) Help on
built-in function strip:
strip (...) method of Builtins.str Instance
S.strip ([chars])-> str return
a copy of the string S with leading and trailing
whitespace Remov Ed.
If chars is given and not None, remove characters in chars instead.
Returns a copy of the string s that removes the beginning and trailing spaces. If chars is specified, the character specified by this chars is deleted.
eg.
' Import OS man=[] other=[] try:data=open (' Sketch.txt ') for Each_line in Data:try: (Role,line_spoken) =each_line.split (': ', 1) #把剧本的分割一次, each row encounters the first: split once, then continue to the next line #
Print (role,end= ') Line_spoken=line_spoken.strip () #返回去掉开头和结尾空格的字符串 if role = = ' man ': Man.append (line_spoken) Elif = = ' other man '
: Other.append (Line_spoken) #print (' said: ', end= ')
#print (line_spoken,end= ') except Valueerror:pass data.close ()
Except Ioerror:print (' The datafile is missing! ') Try:man_file=open (' Man_data.txt ', ' W ') other_file=open (' Other_data.txt ', ' W ') # print (man) # Print (other) print (Man,file=man_file) #将man保存到man_file print (Other,fiLe=other_file) except Ioerror:print (' file error. ') Finally:man_file.close () Other_file.close () #print (Mans)