Python 如何计算文件中的所有行、字和字符
我正在尝试编写一个程序,计算.txt文件中的所有行、字和字符。我有台词出来,但我不知道如何做的话或字符Python 如何计算文件中的所有行、字和字符,python,file,Python,File,我正在尝试编写一个程序,计算.txt文件中的所有行、字和字符。我有台词出来,但我不知道如何做的话或字符 """Write a function stats() that takes one input argument: the name of a text file. The function should print, on the screen, the number of lines, words, and characters in the file; your funct
"""Write a function stats() that takes one input argument: the name of a text file.
The function should print, on the screen, the number of lines, words,
and characters in the file; your function should open the file only once.
stats( 'example.txt') line count: 3 word count: 20 character count: 98"""
def stats(inF):
inFile=open(inF,'r')
text=inFile.readlines()
textLen=len(text)
print(textLen)
wordCount=0
charCount=0
for word in inFile.read().split():
if word in inFile:
wordCount = + 1
else:
wordCount = 1
print(wordCount)
print(stats("n.txt"))
我将为您指出正确的方向,不是最好的python编码器,但这是您希望以逻辑方式解决它的方式。此外,这还考虑到您不希望将“”或“.”计算为字符
inFile=open(inF,'r')
for line in inFiler:
linecount++
#use a tokenizer to find words
newWord = true
for character in line:
#something like this
if newWord:
if character is not listOfNoneValidCharacters(" ", ".", ...etc):
newWord = false
charCount += 1
wordCount += 1
if not newWord:
if character is not listOfNoneValidCharacters:
charCount += 1
newWord = true
每当您在python中执行文件I/O时,我都会建议使用
和()。另外,在每行上迭代,而不是使用infle.read()
。如果你有一个大文件,你的机器内存将感谢你
def stats(inF):
num_lines = 0
num_words = 0
num_chars = 0
with open(inF, 'r') as input_file:
for line in input_file:
num_lines += 1
line_words = line.split()
num_words += len(line_words)
for word in line_words:
num_chars += len(word)
print 'line count: %i, word count: %i, character count: %i' % (num_lines, num_words, num_chars)
stats('test.txt')
你试过什么?你认为你应该试试什么?我们不能只是把答案贴到你的家庭作业上。你已经在做单词了——或者是接近单词的东西了。对于字符,只需在计算行数的同一位置计算行长的总和,这不是我准备考试的家庭作业。