Py学习  »  Python

在文本文件Python中搜索大写单词的数量

Fulltimehustle • 4 年前 • 664 次点击  

我需要帮助整理文本文件

我试过多种不同的for循环。我还试着去掉所有空格,并在文件中逐个计算字母数。我还尝试了strip函数的多种变体和不同的if语句

for character in file:
    if character.isupper():
        capital += 1
        file.readline().rstrip()
        break

print(capital)

我希望程序读取文档中的每个单词或字母,并返回其中包含的大写单词总数。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54929
 
664 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Aivar Paalberg
Reply   •   1 楼
Aivar Paalberg    4 年前

with open('my_textfile.txt', 'r') as text:
    print(sum(word.istitle() for row in text for word in row))
Brandon
Reply   •   2 楼
Brandon    4 年前

两件事:

  1. 确保你是在字符而不是单词或句子上迭代。把一些打印的报表检查一下。
  2. 删除if块中的break语句。这是立即退出你的循环,将导致你只有计数1。
for sentence in file:
    for char in sentence:
        if char.isupper():
            capital += 1

print(capital)
Matt
Reply   •   3 楼
Matt    4 年前

假设我们有一个示例文件 doc.txt 内容如下:

这是一个识别大写单词的测试文件。 我创建这个示例是因为问题的需求可能会有所不同。 例如,像SQL这样的首字母缩略词应该算作大写吗? 如果是:这将导致九个。

如果要计算大写(也称为标题大小写)单词,但排除所有大写单词(如首字母缩略词),可以执行以下操作:

def count_capital_words(filename):                                               
    count = 0                                                                    
    with open(filename, 'r') as fp:                                              
        for line in fp:                                                          
            for word in line.split():                                            
                if word.istitle():                                               
                    print(word)                                                  
                    count += 1                                                   
    return count


print(count_capital_words('doc.txt'))  # 8

filter(None, ...) 功能将确保 word IndexError 如果是这样的话:

def count_capital_words(filename):                                               
    count = 0                                                                    
    with open(filename, 'r') as fp:                                              
        for line in fp:                                                          
            for word in filter(None, line.split()):                              
                if word[0].isupper():                                            
                    count += 1                                                   
    return count


print(count_capital_words('doc.txt'))  # 9

from itertools import chain                                                      


def get_words(filename):                                                         
    with open(filename, 'r') as fp:                                              
        words = chain.from_iterable(line.split() for line in fp)                 
        yield from words