gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:04:52 26 4
gpt4 key购买 nike

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

I am not a robot

I am a human

应该返回:

I

am

not

a

robot

human

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

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 创建的文本文件中没有任何内容。我不确定我做错了什么

最佳答案

for word in word_list:
if word not in word_list:

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

代替该逻辑,使用 set :

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

set 仅包含唯一成员,这正是您要实现的目标。

请注意,不会保留顺序,但您没有指定这是否是必需的。

关于python - 如何使用 Python 从文本文件中返回唯一的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22978602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com