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 仅保留唯一的行。
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)