【发布时间】:2013-05-29 21:43:02
【问题描述】:
我有一个词汇文件,其中包含我需要在其他文本文档中找到的单词。如果有的话,我需要找出每个单词的数量。例如:
词汇表.txt:
thought
await
thorough
away
red
test.txt:
I thought that if i await thorough enough, my thought would take me away.
Away I thought the thought.
最后,我应该看到有 4 个思想实例,1 个等待,2 个离开,1 个彻底,0 个红色。我试过这样:
for vocabLine in vocabOutFile:
wordCounter = 0
print >> sys.stderr, "Vocab word:", vocabLine
for line in testFile:
print >> sys.stderr, "Line 1 :", line
if vocabLine.rstrip('\r\n') in line.rstrip('\r\n'):
print >> sys.stderr, "Vocab word is in line"
wordCounter = wordCounter + line.count(vocabLine)
print >> sys.stderr, "Word counter", wordCounter
testFile.seek(0, 0)
我有一种奇怪的感觉,由于 vocab 文件中的返回字符,它无法识别文件中的单词,因为在调试过程中我确定它正确计算了字符串末尾的任何单词匹配。但是,使用 rstrip() 后,计数仍然不正确。完成这一切后,我必须从词汇表中删除不超过 2 次的单词。
我做错了什么?
谢谢!
【问题讨论】:
-
testFile是文件对象吗? -
是的,testFile 和 vocabOutFile 都是文件对象
-
应该算“离开”吗?看起来是的。你应该在某处规范化大小写(例如在字符串上调用
.lower()) -
那么你得到了什么输出做?
-
第一次通过后,testFile 将位于末尾,因此在后续通过时将跳过该循环。您需要重新打开文件或回到开头