单词和行索引程序



我最初在这里发布了这个问题,但后来被告知将其发布到代码审查中;但是,他们告诉我我的问题需要发布在这里。我会尝试更好地解释我的问题,所以希望没有混淆。我正在尝试编写一个单词索引程序,该程序将执行以下操作:

1( 将stop_words.txt文件读入仅包含停用词的字典(使用与您计时的相同类型的字典(,称为 stopWordDict。(警告:在将换行符添加到 stopWordDict 之前,请从停用词的末尾去除换行符(''

( 字符(2(处理战争与和平.txt一次一行地归档以构建单词索引字典(称为wordConcordanceDict(,其中包含键的"主要"单词,并列出其关联的行号作为其值。

3( 按键按字母顺序遍历单词ConcordanceDict,以生成一个文本文件,其中包含按字母顺序打印的索引单词及其相应的行号。

我在一个小文件上测试了我的程序,其中包含一个简短的停用词列表,它工作正常(在下面提供了一个例子(。结果是我所期望的,一个主要单词及其行数的列表,不包括stop_words_small.txt文件中的单词。我测试的小文件和我实际尝试测试的主文件之间的唯一区别是主文件要长得多并且包含标点符号。所以我遇到的问题是,当我使用主文件运行我的程序时,我得到的结果比预期的要多得多。我得到的结果比预期的要多的原因是标点符号没有从文件中删除。

例如,下面是结果的一部分,我的代码将单词 Dmitri 计算为四个单独的单词,因为单词后面的大写和标点符号不同。如果我的代码要正确删除标点符号,则单词 Dmitri 将计为一个单词,后跟找到的所有位置。我的输出也是分隔大写和小写单词,所以我的代码也没有使文件小写。

我的代码当前显示的内容:

Dmitri : [2528, 3674, 3687, 3694, 4641, 41131]
Dmitri! : [16671, 16672]
Dmitri, : [2530, 3676, 3685, 13160, 16247]
dmitri : [2000]

我的代码应该显示什么:

dmitri : [2000, 2528, 2530, 3674, 3676, 3685, 3687, 3694, 4641, 13160, 16671, 16672, 41131]

单词被定义为由任何非字母分隔的字母序列。大写和小写字母之间也不应该有区别,但我的程序也会将它们分开;但是,空白行将计入行号。

下面是我的代码,如果有人可以看看它并就我做错了什么给我任何反馈,我将不胜感激。提前谢谢你。

import re
def main():
stopFile = open("stop_words.txt","r")
stopWordDict = dict()
for line in stopFile:
stopWordDict[line.lower().strip("n")] = []
hwFile = open("WarAndPeace.txt","r")
wordConcordanceDict = dict()
lineNum = 1
for line in hwFile:
wordList = re.split(" |n|.|"|)|(", line)
for word in wordList:
word.strip(' ')
if (len(word) != 0) and word.lower() not in stopWordDict:
if word in wordConcordanceDict:
wordConcordanceDict[word].append(lineNum)
else:
wordConcordanceDict[word] = [lineNum]
lineNum = lineNum + 1
for word in sorted(wordConcordanceDict):
print (word," : ",wordConcordanceDict[word])

if __name__ == "__main__":
main()

这里的另一个例子和参考是我用一小堆停用词测试的小文件,效果很好。

stop_words_small.txt文件

a, about, be, by, can, do, i, in, is, it, of, on, the, this, to, was

small_file.txt

This is a sample data (text) file to
be processed by your word-concordance program.
The real data file is much bigger.

正确的输出

bigger: 4
concordance: 2
data: 1 4
file: 1 4
much: 4
processed: 2
program: 2
real: 4
sample: 1
text: 1
word: 2
your: 2

你可以这样做:

import re
from collections import defaultdict
wordConcordanceDict = defaultdict(list)
with open('stop_words_small.txt') as sw:
words = (line.strip() for line in sw)
stop_words = set(words)
with open('small_file.txt') as f:
for line_number, line in enumerate(f, 1):
words = (re.sub(r'[^ws]','',word).lower() for word in line.split())
good_words = (word for word in words if word not in stop_words)
for word in good_words:
wordConcordanceDict[word].append(line_number)
for word in sorted(wordConcordanceDict):
print('{}: {}'.format(word, ' '.join(map(str, wordConcordanceDict[word]))))

输出:

bigger: 4
data: 1 4
file: 1 4
much: 4
processed: 2
program: 2
real: 4
sample: 1
text: 1
wordconcordance: 2
your: 2

 我明天再补充解释,;)这里已经很晚了。同时,您可以在注释中询问代码的某些部分是否不清楚。

最新更新