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

11

如何使用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()

Python创建的文本文件中什么都没有。我不确定我做错了什么。

9个回答

17
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 只包含唯一成员,这正是你想要实现的。

请注意,顺序不会被保留,但你没有指定它是否是一个要求。


2
很遗憾,我不能使用set命令,因为这个作业是为了提高我们的for循环技能。 - user927584
2
我很乐意帮助解决作业问题,但是当某些正确的方法被任意禁止时,你必须在一开始就清楚地定义约束条件。 - mhlester
我的错误,我们可以使用任何方法。30分钟前收到了一封电子邮件。 - user927584

6

只需在文件中迭代每行,并使用set来保留唯一的行。

from itertools import chain

def unique_words(lines):
    return set(chain(*(line.split() for line in lines if line)))

那么,只需要按照以下步骤读取文件中的所有唯一行并打印它们。
with open(filename, 'r') as f:
    print(unique_words(f))

2
今日免费次数已满, 请开通会员/明日再来
...
import collections
d = collections.OrderedDict()
for word in wordlist: d[word] = None 
# use this if you also want to count the words:
# for word in wordlist: d[word] = d.get(word, 0) + 1 
for k in d.keys(): print k

您还可以使用collection.Counter(),它也会计算您输入的元素数量。不过单词的顺序会丢失。我添加了一行代码来保持计数和顺序。


2
string = "I am not a robot\n I am a human"
list_str = string.split()
print list(set(list_str))

甚至无法在原帖提供的输入上运行。提示:.split().split(' ') 是不同的。 - trent
@trentcl 现在怎么样?...谢谢,我明白了...真的是一个很好的点,.split().split(' ')之间的区别。 - frp farhan
更好了,但说实话,这个问题已经超过3年了,被接受的答案基本上和你的一样,只是有解释,所以我选择了那个回答。如果你有一些有建设性的东西要补充,比如可能在没有把整个文件加载到内存中的情况下构建集合,那么这将是一个很好的答案;如果答案简单地归结为“使用set”,我不知道你为什么要费心回答。 - trent

1
使用正则表达式和集合:
import re
words = re.findall('\w+', text.lower())
uniq_words = set(words)

另一种方法是创建一个字典,并将单词插入为键:
for i in range(len(doc)):
        frase = doc[i].split(" ")
        for palavra in frase:
            if palavra not in dict_word:
                dict_word[palavra] = 1
print dict_word.keys()

1
def unique_file(input_filename, output_filename):
    input_file = open(input_filename, 'r')
    file_contents = input_file.read()
    input_file.close()
    duplicates = []
    word_list = file_contents.split()
    file = open(output_filename, 'w')
    for word in word_list:
        if word not in duplicates:
            duplicates.append(word)
            file.write(str(word) + "\n")
    file.close()

这段代码循环遍历每个单词,如果它不在列表duplicates中,则将其添加并写入文件。

不需要额外的列表,可以使用以下代码:file = open(output_filename, 'a')。(这是我的第一段代码(但它没有起作用)) - user927584

0
使用集合。您无需导入任何内容即可执行此操作。
#Open the file
my_File = open(file_Name, 'r')
#Read the file
read_File = my_File.read()
#Split the words
words = read_File.split()
#Using a set will only save the unique words
unique_words = set(words)
#You can then print the set as a whole or loop through the set etc
for word in unique_words:
     print(word)

0
你的代码问题在于word_list已经包含了输入文件中所有可能的单词。当循环迭代时,实际上是在检查word_list中的一个单词是否不存在于自身中。因此结果永远是false。这个代码应该可以工作。。(请注意,这也会保留顺序)。
def unique_file(input_filename, output_filename):
  z = []
  with open(input_filename,'r') as fileIn, open(output_filename,'w') as fileOut:
      for line in fileIn:
          for word in line.split():
              if word not in z:
                 z.append(word)
                 fileOut.write(word+'\n')

-2
try:
    with open("gridlex.txt",mode="r",encoding="utf-8")as india:

        for data in india:
            if chr(data)==chr(data):
                print("no of chrats",len(chr(data)))
            else:
                print("data")
except IOError:
    print("sorry")

虽然这个回答可能解决问题,但最好加上一些描述,说明这个回答如何解决问题。请阅读《如何撰写一个好的回答》以了解更多信息。- 来自审查 - Roshana Pitigala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接