【问题标题】:Open a folder, write the top 100 words that appear on text files in the specified folder打开一个文件夹,在指定文件夹中写入文本文件中出现的前 100 个单词
【发布时间】:2018-01-05 19:08:16
【问题描述】:

我想编写一个名为LexicalAnalyzer 的类,在这个类中,我必须根据文件夹目录编写以下函数。 gettop100words:返回一个dictionary在该文件夹的文本文件中找到的整体前100个单词的频率,不关心CAPS。

get_letter_frequencies:返回字母(a-z)频率的dictionary

我该如何写这个LexicalAnalyzer

【问题讨论】:

标签: python python-3.x


【解决方案1】:

只需在文件(文本文件 ofc)中执行 for 循环并添加每个单词及其出现的次数并返回字典。要拆分单词,只需将文件的整个文本添加到一个字符串中,并使用拆分函数将单词分成列表并循环遍历它,然后执行我在乞讨时告诉你的字典。

【讨论】:

    【解决方案2】:
    1. fileinput 中使用以遍历文件
    2. collections.Counter 中用于计数对象(单词、字母)

    示例

    环境:

    $ tree /tmp/test
    /tmp/test
    ├── file1.txt
    ├── file2.txt
    └── file3.txt
    
    0 directories, 3 files
    

    数据:

    $ tail -vn +1 /tmp/test/*.txt
    ==> /tmp/test/file1.txt <==
    hello world
    world foo bar egg
    spam egg baz
    end
    
    ==> /tmp/test/file2.txt <==
    foo xxx yyy
    qqq foo
    eee ttt def
    cmp
    
    ==> /tmp/test/file3.txt <==
    Foo BAR
    SpAm
    

    片段:

    import os
    import fileinput
    import collections
    
    DIR = '/tmp/test'
    
    files = [os.path.join(DIR, filename) for filename in os.listdir(DIR)]
    words = collections.Counter()
    letters = collections.Counter()
    
    with fileinput.input(files=files) as f:
        for line in f:
            words.update(line.lower().split())
    
    for word in words:
        letters.update(word)
    
    # top 3 word
    print(words.most_common(3))
    
    # top 5 letters
    print(letters.most_common(5))
    

    输出:

    [('foo', 4), ('egg', 2), ('spam', 2)]
    [('e', 7), ('o', 4), ('y', 3), ('l', 3), ('q', 3)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多