如何使用Python从文本文件中返回唯一的单词

use*_*584 7 python unique text-files

如何使用Python返回文本文件中的所有唯一单词?例如:

我不是机器人

我是一个人

应该返回:

一世

上午

一个

机器人

人的

这是我到目前为止所做的:

def unique_file(input_filename, output_filename):
    input_file = open(input_filename, 'r')
    file_contents = input_file.read()
    input_file.close()
    word_list = file_contents.split()

    file = open(output_filename, 'w')

    for word in word_list:
        if word not in word_list:
            file.write(str(word) + "\n")
    file.close()
Run Code Online (Sandbox Code Playgroud)

Python创建的文本文件中没有任何内容.我不确定我做错了什么

mhl*_*ter 10

for word in word_list:
    if word not in word_list:
Run Code Online (Sandbox Code Playgroud)

根据定义,每一个word都在word_list第一行.

而不是那个逻辑,使用set:

unique_words = set(word_list)
for word in unique_words:
    file.write(str(word) + "\n")
Run Code Online (Sandbox Code Playgroud)

sets只保留独特的成员,这正是你想要实现的目标.

请注意,订单不会被保留,但您没有指定是否需要.

  • 不幸的是,我不能使用 set 命令,因为这个作业是为了提高我们的 for 循环技能。 (2认同)
  • 我在帮助完成家庭作业问题时没有任何问题,但是当正确地禁止做某事的正确方法时,你必须明确地预先确定约束条件. (2认同)

agr*_*inh 5

只需遍历文件中的行并使用 set 仅保留唯一的行。

from itertools import chain

def unique_words(lines):
    return set(chain(*(line.split() for line in lines if line)))
Run Code Online (Sandbox Code Playgroud)

然后只需执行以下操作即可从文件中读取所有唯一行并打印它们

with open(filename, 'r') as f:
    print(unique_words(f))
Run Code Online (Sandbox Code Playgroud)