python 输出文件a.txt中的字符个数不含回车,使用Python查找文件中的字符数

Here is the question:

I have a file with these words:

hey how are you

I am fine and you

Yes I am fine

And it is asked to find the number of words, lines and characters.

Below is my program, but the number of counts for the characters without space is not correct.

The number of words is correct and the number of line is correct.

What is the mistake in the same loop?

fname = input("Enter the name of the file:")

infile = open(fname, 'r')

lines = 0

words = 0

characters = 0

for line in infile:

wordslist = line.split()

lines = lines + 1

words = words + len(wordslist)

characters = characters + len(line)

print(lines)

print(words)

print(characters)

The output is:

lines=3(Correct)

words=13(correct)

characters=47

I've looked on the site with multiple answers and I am confused because I didn't learn some other functions in Python. How do I correct the code as simple and basic as it is in the loop I've done?

Whereas the number of characters without space is 35 and with space is 45.

If possible, I want to find the number of characters without space. Even if someone know the loop for the number of characters with space that's fine.

解决方案

Sum up the length of all words in a line:

characters += sum(len(word) for word in wordslist)

The whole program:

with open('my_words.txt') as infile:

lines=0

words=0

characters=0

for line in infile:

wordslist=line.split()

lines=lines+1

words=words+len(wordslist)

characters += sum(len(word) for word in wordslist)

print(lines)

print(words)

print(characters)

Output:

3

13

35

This:

(len(word) for word in wordslist)

is a generator expression. It is essentially a loop in one line that produces the length of each word. We feed these lengths directly to sum:

sum(len(word) for word in wordslist)

Improved version

This version takes advantage of enumerate, so you save two lines of code, while keeping the readability:

with open('my_words.txt') as infile:

words = 0

characters = 0

for lineno, line in enumerate(infile, 1):

wordslist = line.split()

words += len(wordslist)

characters += sum(len(word) for word in wordslist)

print(lineno)

print(words)

print(characters)

This line:

with open('my_words.txt') as infile:

opens the file with the promise to close it as soon as you leave indentation.

It is always good practice to close file after your are done using it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值