【发布时间】: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