【问题标题】:Count the number of characters in every word of every line of a file计算文件每一行的每个单词的字符数
【发布时间】:2015-09-30 23:25:34
【问题描述】:

此代码将打印文本文件中的总行数、总字数和总字符数。它工作正常并提供预期的输出。但我想计算每行中的字符数并像这样打印:-

Line No. 1 has 58 Characters
Line No. 2 has 24 Characters

代码:-

import string
def fileCount(fname):
    #counting variables
    lineCount = 0
    wordCount = 0
    charCount = 0
    words = []

    #file is opened and assigned a variable
    infile = open(fname, 'r')

    #loop that finds the number of lines in the file
    for line in infile:
        lineCount = lineCount + 1
        word = line.split()
        words = words + word

    #loop that finds the number of words in the file
    for word in words:
        wordCount = wordCount + 1
        #loop that finds the number of characters in the file
        for char in word:
            charCount = charCount + 1
    #returns the variables so they can be called to the main function        
    return(lineCount, wordCount, charCount)

def main():
    fname = input('Enter the name of the file to be used: ')
    lineCount, wordCount, charCount = fileCount(fname)
    print ("There are", lineCount, "lines in the file.")
    print ("There are", charCount, "characters in the file.")
    print ("There are", wordCount, "words in the file.")
main()

作为

for line in infile:
    lineCount = lineCount + 1 

正在计算整行,但是如何为该操作取每一行? 我正在使用 Python 3.X

【问题讨论】:

  • 你可以使用len函数。
  • 但 len 也会计算空格和制表符。另外,如何将它应用于每一行?我需要另一个循环。
  • len(re.findall(r'\S', line))
  • 不需要为此使用正则表达式
  • Python 有一个超级有用的内置函数collections.Counter,它是一个专门计算其输入的字典。看我的回答。更短的代码和更高的性能,因为无需迭代地追加到您的列表words

标签: python text count counter word-count


【解决方案1】:

将所有信息存储在字典中,然后通过密钥访问。

def fileCount(fname):
    #counting variables
    d = {"lines":0, "words": 0, "lengths":[]}
    #file is opened and assigned a variable
    with open(fname, 'r') as f:
        for line in f:
            # split into words
            spl = line.split()
            # increase count for each line
            d["lines"] += 1
            # add length of split list which will give total words
            d["words"] += len(spl)
            # get the length of each word and sum
            d["lengths"].append(sum(len(word) for word in spl))
    return d

def main():
    fname = input('Enter the name of the file to be used: ')
    data = fileCount(fname)
    print ("There are {lines} lines in the file.".format(**data))
    print ("There are {} characters in the file.".format(sum(data["lengths"])))
    print ("There are {words} words in the file.".format(**data))
    # enumerate over the lengths, outputting char count for each line
    for ind, s in enumerate(data["lengths"], 1):
        print("Line: {} has {} characters.".format(ind, s))
main()

该代码仅适用于由空格分隔的单词,因此您需要牢记这一点。

【讨论】:

【解决方案2】:

定义您希望计数的允许字符的set,然后您可以使用len 获取大部分数据。
下面,我选择了字符集:

['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ', ', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'、':'、';'、''、'?'、'@'、'A'、'B'、'C'、'D'、'E ','F','G','H','I','J','K','L','M','N','O','P','Q', 'R'、'S'、'T'、'U'、'V'、'W'、'X'、'Y'、'Z'、'['、'\'、']'、'^ ','_','`','a','b','c','d','e','f','g','h','i','j', 'k'、'l'、'm'、'n'、'o'、'p'、'q'、'r'、's'、't'、'u'、'v'、'w '、'x'、'y'、'z'、'{'、'|'、'}'、'~']

#Define desired character set
valid_chars = set([chr(i) for i in range(33,127)])
total_lines = total_words = total_chars = 0
line_details = []

with open ('test.txt', 'r') as f:
    for line in f:
        total_lines += 1
        line_char_count = len([char for char in line if char in valid_chars])
        total_chars += line_char_count
        total_words += len(line.split())
        line_details.append("Line %d has %d characters" % (total_lines, line_char_count))

print ("There are", total_lines, "lines in the file.")
print ("There are", total_chars, "characters in the file.")
print ("There are", total_words, "words in the file.")
for line in line_details:
    print (line)

【讨论】:

    【解决方案3】:

    我的任务是创建一个打印一行中字符数的程序。

    作为一个编程菜鸟,我发现这非常困难:(。

    这是我想出的,以及他的回应 -

    这是程序的核心部分:

    with open ('data_vis_tips.txt', 'r') as inFile:
        with open ('count_chars_per_line.txt', 'w') as outFile:
            chars = 0
                for line in inFile:
                    line = line.strip('\n')
                    chars = len(line)
                    outFile.write(str(len(line))+'\n')
    

    可以简化为:

    with open ('data_vis_tips.txt', 'r') as inFile:
        for line in inFile:
            line = line.strip()
            num_chars = len(line)
            print(num_chars)
    

    请注意,strip() 函数的参数不是必需的;它默认去除空格,'\n' 是空格。

    【讨论】:

      【解决方案4】:

      这是一个使用内置 collections.Counter 的更简单版本,这是一个专门计算其输入的字典。我们可以使用Counter.update() 方法在每一行中插入所有单词(唯一或非唯一):

      from collections import Counter
      
      def file_count_2(fname):
      
          line_count = 0
          word_counter = Counter()
      
          infile = open(fname, 'r')
          for line in infile:
              line_count += 1
              word_counter.update( line.split() )
      
          word_count = 0
          char_count = 0
      
          for word, cnt in word_counter.items():
              word_count += cnt
              char_count += cnt * len(word)
      
          print(word_counter)
      
          return line_count, word_count, char_count
      

      注意事项:

      • 我对此进行了测试,它为您的代码提供了相同的计数
      • 它会更快,因为您没有迭代地附加到列表words(最好只散列唯一的单词并存储它们的计数,这就是 Counter 所做的),也不需要迭代和递增charCount 每次我们看到一个单词的出现。
      • 如果你只想要word_count 而不是char_count,你可以直接取word_count = sum(word_counter.values()) 而无需遍历word_counter

      【讨论】:

      • PS 命名word_countline_count 等比wordCountlineCount 更Pythonic(PEP-8 格式);我们只对类名使用 CamelCase,而不是变量、函数或方法。
      • 虽然这个答案可能比原始代码更有效,但它没有回答“如何计算和打印每行中的字符数”的问题。
      • @RolfofSaxony:确实如此,per OP's original title and code example. The title edit was mine, not theirs, trying to capture their intent。我现在已经修复它以明确 “每行的每个单词” 而不是 “每行的每个单词”
      • 来自问题:“第 1 行有 58 个字符第 2 行有 24 个字符”??
      • @RolfofSaxony:啊,我将 OP 的代码作为他们想要的规范,并对其进行了清理。但他们想将其扩展到每行内的计数。让我更正我的代码...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多