【发布时间】:2014-04-04 19:23:12
【问题描述】:
所以我正在研究这个文本挖掘项目。我正在尝试打开所有文件,获取组织和摘要的信息,在摘要中拆分单词,然后找出每个单词显示多少文件。 我的问题是关于最后一步:一个词显示多少个文件?为了回答这个问题,我正在制作一个字典 wordFrequency 来计算它。我试图告诉字典:如果字典中没有出现单词,则捕获该单词和附加的文件编号;如果字典中显示了一个单词,但文件号与任何现有的不同,则在其后面附加文件号。如果单词及其文件号都已在字典中,则忽略它。下面是我的代码。
capturedfiles = []
capturedabstracts = []
wordFrequency = {}
wordlist=open('test.txt','w')
worddict=open('test3.txt','w')
for filepath in matches[0:5]:
with open (filepath,'rt') as mytext:
mytext=mytext.read()
#print mytext
# code to capture file organizations.
grabFile=re.findall(r'File\s+\:\s+(\w\d{7})',mytext)
if len(grabFile) == 0:
matchFile= "N/A"
else:
matchFile = grabFile[0]
capturedfiles.append(matchFile)
# code to capture file abstracts
grabAbs=re.findall(r'Abstract\s\:\s\d{7}\s(\w.+)',mytext)
if len(grabAbs) == 0:
matchAbs= "N/A"
else:
matchAbs = grabAbs
capturedabstracts.append(matchAbs)
# arrange words in format.
lineCount = 0
wordCount = 0
lines = matchAbs[0].split('. ')
for line in lines:
lineCount +=1
for word in line.split(' '):
wordCount +=1
wordlist.write(matchFile + '|' + str(lineCount) + '|' + str(wordCount) + '|' + word + '\n')
if word not in wordFrequency:
wordFrequency[word]=[matchFile]
else:
if matchFile not in wordFrequency[word]:
wordFrequency[word].append(matchFile)
worddict.write(word + '|' + str(matchFile) + '\n')
wordlist.close()
worddict.close()
我现在得到的是每个单词都打印出与其匹配的文件号。如果一个单词在整个文本中出现两次,它将分别打印两次。以下是它的外观示例:
变体|a9500006 是|a9500006 是|a9500007
我希望它看起来像:
变体|a9500006 是|a9500006, a9500007
【问题讨论】:
-
您想要的行为正是
dict对象的工作方式,这里的问题在于您打印文本的方式。如果您只打印 dict,您应该会看到与多个值配对的键。 -
当我尝试
print wordFrequency时,它反复打印出结果。当我把它写在另一个文件中时,每个单词都被列出来了。如果一个词在一个文件或多个文件中出现多次,它们都会单独列出。 -
将
print wordFrequency放在任何循环之外和代码的底部。 -
我只是尝试输入
print语句,它会循环打印相同的结果。不能再往外移,否则会出现错误信息“unexpected indentatio”。另外,我想把它写到一个文件中,对代码有什么建议吗?谢谢。 -
"不能将它移到外面,否则会出现错误消息"unexpected indentatio"。"你试过取消缩进吗?
标签: python-2.7 dictionary