我正在写计算所有行,单词和汉字是从给定的输入文件的程序。
import string
def main():
print "Program determines the number of lines, words and chars in a file."
file_name = raw_input("What is the file name to analyze? ")
in_file = open(file_name, 'r')
data = in_file.read()
words = string.split(data)
chars = 0
lines = 0
for i in words:
chars = chars + len(i)
print chars, len(words)
main()
在一定程度上,该代码是确定。
我不知道但是如何在文件中算“空间”。 我的性格计数器的计数值只能是字母,空格被排除在外。
加上我一片空白,当谈到计数线。
你可以只用len(data)
的字符长度。
可以拆分data
通过使用线.splitlines()
方法,并且该结果的长度是行数。
但是,更好的方法是逐行读取文件中的行:
chars = words = lines = 0
with open(file_name, 'r') as in_file:
for line in in_file:
lines += 1
words += len(line.split())
chars += len(line)
现在,如果该文件是非常大的程序会甚至工作; 它不会在内存中的时间持有多行(还有一个小缓冲区蟒蛇保持,使for line in in_file:
环快一点)。
很简单:如果你要打印无字符的,没有的话也没有行的文件中。 和包括空格..简短的回答我觉得是我的..
import string
data = open('diamond.txt', 'r').read()
print len(data.splitlines()), len(string.split(data)), len(data)
保持编码哥们...
阅读文件 -
d=fp.readlines()
characters-
sum([len(i)-1 for i in d])
线 -
len(d)
话-
sum([len(i.split()) for i in d])
这是不使用任何关键字字数统计的一个粗暴的方式:
#count number of words in file
fp=open("hello1.txt","r+");
data=fp.read();
word_count=1;
for i in data:
if i==" ":
word_count=word_count+1;
# end if
# end for
print ("number of words are:", word_count);