2
此代碼將打印文本文件中的整行數,總字數和字符總數。它工作正常,並提供預期產出。但是,我希望計算每行的字符數,並打印這樣的: -計算每行中的字符數
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也會計算空格和製表符。另外,如何將它應用於每一行?我需要另一個循環。 – cyberoy
'len(re.findall(r'\ S',line))' –