【发布时间】:2018-10-11 22:38:11
【问题描述】:
我最初在这里发布了这个问题,但后来被告知将其发布到代码审查;但是,他们告诉我,我的问题需要在这里发布。我将尝试更好地解释我的问题,所以希望没有混淆。我正在尝试编写一个单词索引程序,它将执行以下操作:
1) 将 stop_words.txt 文件读入一个只包含停用词的词典(使用与您计时的相同类型的词典),称为 stopWordDict。 (警告:在将停用词添加到 stopWordDict 之前,去掉换行符('\n')字符)
2) 一次处理一行 WarAndPeace.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
【问题讨论】:
标签: python punctuation