我正在尝试编写一个程序来计算.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 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编写I/O文件时,我都会使用
with
(docs)来提示。另外,迭代每一行,而不是使用inFile.read()
。如果你有一个大文件,你的机器内存会感谢你。在我会给你指出一个正确的方向,不是最好的python代码编写器,但这就是你想要逻辑地解决它的方法。另外,这也考虑到您不想将“”或“.”计为字符。在
相关问题 更多 >
编程相关推荐