列出并计算 Word 文档中的唯一单词

Sup*_*ken 0 statistics word-count microsoft-word

我想要获取一个 Microsoft Word 文档并生成一个电子表格,其中包含该文档中包含的所有单词以及每个单词出现的次数。

例如,

cat    23
said   15
jumped 12
dog    7
Run Code Online (Sandbox Code Playgroud)

这是一个简单的问题,可以使用 Word 或 Excel 的内置函数和特性以简单、直接的方式完成吗?

如果没有,此功能是否可以在现成的工具中轻松使用(在这种情况下,请告知我应该在 Software Recs 站点上查询什么内容),还是需要自定义编程?

Gan*_*sek 5

除了VBA之外,还可以使用OpenOffice的API来开发这样一个应用程序来读取Word文档的内容;对其进行处理并将结果导出为 CSV 文件以在电子表格应用程序中打开。

然而,如果您熟悉任何编程语言,它实际上只是几行代码。例如,在 Python 中,您可以轻松地这样做:

这里我们定义一个简单的函数来计算给定列表的单词数

def countWords(a_list):
    words = {}
    for i in range(len(a_list)):
        item = a_list[i]
        count = a_list.count(item)
        words[item] = count
    return sorted(words.items(), key = lambda item: item[1], reverse=True)
Run Code Online (Sandbox Code Playgroud)

剩下的就是操作文档内容了。先贴一下:

content = """This is the content of the word document. Just copy paste it. 
It can be very very very very long and it can contain punctuation 
(they will be ignored) and numbers like 123 and 4567 (they will be counted)."""
Run Code Online (Sandbox Code Playgroud)

在这里,我们删除标点符号、EOL、括号等,然后为我们的函数生成一个单词列表:

import re

cleanContent = re.sub('[^a-zA-Z0-9]',' ', content)

wordList = cleanContent.lower().split()
Run Code Online (Sandbox Code Playgroud)

然后我们运行我们的函数并将其结果(字数对)存储在另一个列表中并打印结果:

result = countWords(wordList)

for words in result:
    print(words)
Run Code Online (Sandbox Code Playgroud)

所以结果是:

('very', 4)
('and', 3)
('it', 3)
('be', 3)
('they', 2)
('will', 2)
('can', 2)
('the', 2)
('ignored', 1)
('just', 1)
('is', 1)
('numbers', 1)
('punctuation', 1)
('long', 1)
('content', 1)
('document', 1)
('123', 1)
('4567', 1)
('copy', 1)
('paste', 1)
('word', 1)
('like', 1)
('this', 1)
('of', 1)
('contain', 1)
('counted', 1)
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以使用搜索/替换删除括号和逗号。

您所需要做的就是下载Python 3、安装它、打开 IDLE(Python 附带)、替换 Word 文档的内容并按给定顺序一次运行一个命令。