Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在我的输出文件中只需要唯一的单词_Python_File_Python 3.x - Fatal编程技术网

Python 在我的输出文件中只需要唯一的单词

Python 在我的输出文件中只需要唯一的单词,python,file,python-3.x,Python,File,Python 3.x,我正在尝试编写一些代码,以获取一个输入文件,该文件是一段文本(该段具有某些单词的副本),然后我想将该文本写入一个输出文件,但是我不希望将单词的副本写入我的输出文件,只需唯一的单词,这包括一个副本 就我所知,我似乎不知道如何只写一些独特的单词 def unique_file(input_filename, output_filename): input_file = open(input_filename,'r') content = input_file.read()

我正在尝试编写一些代码,以获取一个输入文件,该文件是一段文本(该段具有某些单词的副本),然后我想将该文本写入一个输出文件,但是我不希望将单词的副本写入我的输出文件,只需唯一的单词,这包括一个副本

就我所知,我似乎不知道如何只写一些独特的单词

def unique_file(input_filename, output_filename):

    input_file = open(input_filename,'r')
    content = input_file.read()
    input_file.close()
    word_list = content.split()
    output_file = open(output_filename,'w')

    unique_list = []
        for words in word_list:
            if words not in unique_list:
                output_file.write(words + '\n')
                output_file.close

您可以使用
set

def unique_file(input_filename, output_filename):

    input_file = open(input_filename,'r')
    content = input_file.read()
    input_file.close()
    word_list = content.split()
    output_file = open(output_filename,'w')

    word_list = list(set(word_list))

    for word in word_list:
        output_file.write(words + '\n')
    output_file.close


如果要在中使用非,请执行以下操作:

单词列表是您的单词列表,包含重复的单词

unique_list = []
for word in word_list:
    if word not in unique_list:
        unique_list.append(word)
        output_file.write(word + '\n')
output_file.close()
只要做:

word_list = [word.lower() for word in word_list]
然后:

list(set(word_list))

将给你一个独特的单词列表。Python将自动消除重复项。执行
.lower()
的原因是将
Ball
Ball
视为相同的单词,并且只使用其中一个。如果你想让第一行变成两个单词,就把它去掉。

有没有办法用“不在”来做到这一点?我已经调整了代码,没有收到任何写入输出文件的数据?@MrWallace,是的,这只是一种获得唯一列表的方法,要写入文件,你需要使用
write
@MrWallace,注意:close命令应该在for循环之外