【问题标题】:Trying to find word count in a text file using a different text file as "dictionary"尝试使用不同的文本文件作为“字典”在文本文件中查找字数
【发布时间】: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 将位于末尾,因此在后续通过时将跳过该循环。您需要重新打开文件或回到开头

标签: python string text count


【解决方案1】:

为你的词汇制作一本字典是个好主意。

vocab_counter = {vocabLine.strip().lower(): 0 for vocabLine in vocabOutFile}

然后只扫描 testFile 一次(效率更高),增加每个单词的计数

for line in testFile:
    for word in re.findall(r'\w+', line.lower()):
        if word in vocab_counter:
            vocab_counter[word] += 1

【讨论】:

  • 你好,不知道你是否还在看这个,但是编译器对段有语法问题:vocabLine.strip().lower(): 0 for vocabLine in vocabOutFile由于某种原因它不喜欢 for 语句
  • @FeralShadow,这是一个听写理解。它仅适用于 Python2.7 或更高版本。对于 Python2.6,您可以在 vocabOutFile 中使用 dict((vocabLine.strip().lower(), 0) 来表示 vocabLine)
  • 啊哈好吧!奇怪我怎么没有2.7。谢谢!
  • 所以,还有一个问题:它不会增加任何单词的计数。它的行为就像在字典中找不到单词一样。它正确读取每一行,并在第二个 FOR 循环中正确查看每个单词,但 IF 语句永远不会为真。
  • 啊!抱歉,我错过了您提供的一些代码。它完美无缺!谢谢大佬!
【解决方案2】:

使用regexcollections.Counter

import re
from collections import Counter
from itertools import chain

with open("voc") as v, open("test") as test:
    #create a set of words from vocabulary file
    words = set(line.strip().lower() for line in v) 

    #find words in test file using regex
    words_test = [ re.findall(r'\w+', line) for line in test ]

    #Create counter of words that are found in words set from vocab file
    counter = Counter(word.lower()  for word in chain(*words_test)\
                                          if word.lower() in words)
    for word in words:
        print word, counter[word]

输出

thought 4
away 2
await 1
red 0
thorough 1

【讨论】:

  • 这是一个很好的答案,但这里有很多更高级的 Python (列表推导、itertools.chain、生成器、*args),稍微解释一下可能会很好了解每行代码的工作原理。
猜你喜欢
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多