首页 > 解决方案 > 将文件中的单词附加到其他不同的文件

问题描述

我有一个文本文件,其中的内容是不同人之间的对话。例如-

WILL: Hii , 
ROYCE: Hello , 
WILL: How r u? , 
ROYCE: Fine , 
WILL: Where have h been?

我想为每个字符及其名称创建一个新的文本文件,并将他们所说的唯一单词存储在各自的文件中。我怎样才能使用python做到这一点?

标签: python

解决方案


希望这会有所帮助。为此,我们必须先创建两个单独的文件。

with open('Will.txt', 'r+a') as newfile_1,open('Royce.txt', 'r+a') as newfile_2:
     Will_lines_lst = newfile_1.readlines()
     Royce_lines_lst = newfile_2.readlines()     
     with open('name_file.txt','r+w') as f:
        for line in f:
            if line not in Will_lines_lst and line[0] == 'W':
                 newfile_1.append(line)
            elif line not in Royce_lines_lst:
                 newfile_2.append(line)   

推荐阅读