繁体   English   中英

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

[英]Searching for the amount of capital words in a text file Python

我需要帮助对文本文件进行排序

我尝试了 for 循环的多种变体。 我还尝试去除所有空格并单独计算文件中的字母。 我还尝试了条带 function 的多种变体以及不同的 if 语句

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

print(capital)

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

如果目标是计算以大写字母开头的单词,那么我会使用 boolean 值是 integer 的子类型的事实:

with open('my_textfile.txt', 'r') as text:
    print(sum(word.istitle() for row in text for word in row))

两件事情:

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

print(capital)

假设我们有一个包含以下内容的示例文件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

如果要计算全大写单词,您可以修改 function 以仅检查单词的第一个字母。 请注意, filter(None, ...) function 将确保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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM