Skip to main content
 首页 » 编程设计

python之如何使用 Python 计算文本文档中的唯一单词(没有特殊字符/大小写干扰)

2024年10月24日23lexus

我是 Python 的新手,需要一些帮助来尝试提出一个文本内容分析器,它可以帮助我在一个文本文件中找到 7 个东西:

  1. 总字数
  2. 唯一单词的总数(没有大小写和特殊字符干扰)
  3. 句子数
  4. 一句话中的平均字数
  5. 查找常用短语(包含 3 个或更多单词且使用次数超过 3 次的短语)
  6. 使用的单词列表,按频率降序排列(没有大小写和特殊字符干扰)
  7. 能够接受来自 STDIN 或命令行指定文件的输入

到目前为止,我有这个 Python 程序来打印总字数:

with open('/Users/name/Desktop/20words.txt', 'r') as f: 
 
     p = f.read() 
 
     words = p.split() 
 
     wordCount = len(words) 
     print "The total word count is:", wordCount 

到目前为止,我有这个 Python 程序来打印独特的单词及其频率:(它没有按顺序看到单词,例如:dog、dog.、"dog, 和 dog, 是不同的词)

 file=open("/Users/name/Desktop/20words.txt", "r+") 
 
 wordcount={} 
 
 for word in file.read().split(): 
 
     if word not in wordcount: 
         wordcount[word] = 1 
     else: 
         wordcount[word] += 1 
 for k, v in wordcount.items(): 
     print k, v 

感谢您提供的任何帮助!

请您参考如下方法:

当然,最困难的部分是识别句子。你可以使用 regular expression为此,但可能仍然存在一些歧义,例如带有姓名和头衔,有一个点后跟一个大写字母。对于单词,您也可以使用简单的正则表达式,而不是使用 split。要使用的确切表达取决于什么是“词”。最后,您可以使用 collections.Counter用于计算所有这些而不是手动执行此操作。使用 str.lower 将整个文本或单个单词转换为小写。

这应该可以帮助您入门:

import re, collections 
text = """Sentences start with an upper-case letter. Do they always end  
with a dot? No! Also, not each dot is the end of a sentence, e.g. these two,  
but this is. Still, some ambiguity remains with names, like Mr. Miller here.""" 
 
sentence = re.compile(r"[A-Z].*?[.!?](?=\s+[A-Z]|$)", re.S)     
sentences = collections.Counter(sentence.findall(text)) 
for n, s in sentences.most_common(): 
    print n, s 
 
word = re.compile(r"\w+") 
words = collections.Counter(word.findall(text.lower())) 
for n, w in words.most_common(): 
    print n, w 

为了“更强大”,你可以使用一些 natural language toolkit ,但这对于这项任务来说可能有点过分。