Python 如何计算文件中的句子、单词和字符数?

Python 如何计算文件中的句子、单词和字符数?,python,nltk,Python,Nltk,我编写了以下代码来标记来自samp.txt文件的输入段落。有人能帮我找到并打印文件中的句子、单词和字符数吗?为此,我在python中使用了NLTK >>>import nltk.data >>>import nltk.tokenize >>>f=open('samp.txt') >>>raw=f.read() >>>tokenized_sentences=nltk.sent_tokenize(raw) &g

我编写了以下代码来标记来自samp.txt文件的输入段落。有人能帮我找到并打印文件中的句子、单词和字符数吗?为此,我在python中使用了NLTK

>>>import nltk.data
>>>import nltk.tokenize
>>>f=open('samp.txt')
>>>raw=f.read()
>>>tokenized_sentences=nltk.sent_tokenize(raw)
>>>for each_sentence in tokenized_sentences:
...   words=nltk.tokenize.word_tokenize(each_sentence)
...   print each_sentence   #prints tokenized sentences from samp.txt
>>>tokenized_words=nltk.word_tokenize(raw)
>>>for each_word in tokenized_words:
...   words=nltk.tokenize.word_tokenize(each_word)
...   print each_words      #prints tokenized words from samp.txt

已经有一个计算单词和字符的程序--
wc

  • 字符很容易计数
  • 段落通常也很容易计数。每当你看到两个连续的换行,你可能有一个段落。您可能会说枚举或无序列表是一个段落,即使它们的条目可以用两个新行分隔。标题或标题后面也可以有两行换行符,尽管它们显然不是段落。还要考虑文件中的一个段落的情况,其中有一个或没有新行跟随。
  • 句子很复杂。您可以选择句号、感叹号或问号,后跟空格或文件结尾。这很棘手,因为有时冒号表示句子的结尾,有时则不表示。通常情况下,在英语中,下一个非空白字符将是大写。但有时不是;例如,如果它是一个数字。有时开括号表示句子的结尾(但这是有争议的,就像在本例中)
  • 语言也很复杂。通常单词由空格或标点符号分隔。有时破折号划出一个单词,有时则不是。例如,连字符就是这种情况

对于单词和句子,你可能需要清楚地说明你对一个句子的定义,以及一个单词和程序。

不是100%正确,但我只是试了一下。我没有考虑@wilhelmtell in的所有观点。我一有时间就试一下

if __name__ == "__main__":
   f = open("1.txt")
   c=w=0
   s=1
   prevIsSentence = False
   for x in f:
      x = x.strip()
      if x != "":
        words = x.split()
        w = w+len(words)
        c = c + sum([len(word) for word in words])
        prevIsSentence = True
      else:
        if prevIsSentence:
           s = s+1
        prevIsSentence = False

   if not prevIsSentence:
      s = s-1
   print "%d:%d:%d" % (c,w,s)
这里1.txt是文件名。

这样试试(此程序假定您正在使用
dirpath
指定目录中的一个文本文件):


希望这对nltk有所帮助,您也可以使用FreqDist(请参阅)

就你而言:

import nltk
raw = open('samp.txt').read()
raw = nltk.Text(nltk.word_tokenize(raw.decode('utf-8')))
fdist = nltk.FreqDist(raw)
print fdist.N()

如果有人来这里,这是值得的。我认为这解决了OP提出的所有问题。如果使用
textstat
软件包,计算句子和字符非常容易。每个句子末尾的标点符号都有一定的重要性

import textstat

your_text = "This is a sentence! This is sentence two. And this is the final sentence?"
print("Num sentences:", textstat.sentence_count(your_text))
print("Num chars:", textstat.char_count(your_text, ignore_spaces=True))
print("Num words:", len(your_text.split()))

解决这个问题的唯一方法是创建一个AI程序,使用N自然L语言p处理,这并不容易

输入:

“这是一段关于图灵机器的文章。艾伦·图灵博士发明了图灵机器。它解决了一个有0.1%变化的问题。”

签出OpenNLP


我认为这是正确的解决方案,因为它正确地将“…”和“?”作为一个句子来计算

len(re.findall(r"[^?!.][?!.]", paragraph))
len(re.findall(r"[^?!.][?!.]", paragraph))