如何使用 Python 从文本文件中返回唯一的单词 [英] How to return unique words from the text file using Python

查看:44
本文介绍了如何使用 Python 从文本文件中返回唯一的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I return all the unique words from a text file using Python? For example:

我不是机器人

我是人类

应该返回:

上午

不是

一个

机器人

人类

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

Here is what I've done so far:

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()

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

The text file the Python creates has nothing in it. I'm not sure what I am doing wrong

推荐答案

for word in word_list:
    if word not in word_list:

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

every word is in word_list, by definition from the first line.

代替该逻辑,使用 set:

Instead of that logic, use a set:

unique_words = set(word_list)
for word in unique_words:
    file.write(str(word) + "\n")

sets 只包含唯一成员,这正是您想要实现的.

sets only hold unique members, which is exactly what you're trying to achieve.

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

Note that order won't be preserved, but you didn't specify if that's a requirement.

这篇关于如何使用 Python 从文本文件中返回唯一的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆