【问题标题】:how do I count unique words of text files in specific directory with Python? [closed]如何使用 Python 计算特定目录中文本文件的唯一单词? [关闭]
【发布时间】:2012-08-04 06:23:23
【问题描述】:

我正在写一份报告,我需要计算文本文件的唯一字数。

我的文本在 D:\shakeall 中,总共有 42 个文件...

我对 Python 有所了解,但现在不知道该做什么。

这就是我所知道的。

  1. 读取目录中的文件

  2. 从文本中组成一个单词列表

  3. 统计总字数/唯一字数

我所知道的就是这个。还有一些关于 for、while、列表和索引、变量、列表...

我想做的是制作自己的函数库并使用它来获取结果。

非常感谢任何关于我的问题的建议。

--------附言

我对 Python 几乎一无所知。我只能做一个简单的数学运算或在列表中打印单词……给定的主题对我来说太难了。对不起。

【问题讨论】:

  • 你能把你写的代码贴在这里,让我们看看你尝试了什么吗?
  • 创建一个空的set 并在文件中循环填充单词。然后该集合的len 将是唯一字数。查看os.listdir 对文件的迭代。

标签: python list directory readfile word-count


【解决方案1】:
textfile=open('somefile.txt','r')
text_list=[line.split(' ') for line in textfile]
unique_words=[word for word in text_list if word not in unique_words]
print(len(unique_words))

这就是它的一般要点

【讨论】:

    【解决方案2】:
    import os
    uniquewords = set([])
    
    for root, dirs, files in os.walk("D:\\shakeall"):
        for name in files:
            [uniquewords.add(x) for x in open(os.path.join(root,name)).read().split()]
    
    print list(uniquewords)
    print len(uniquewords)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-15
      • 2020-02-17
      • 2015-06-02
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      相关资源
      最近更新 更多