计算文件的最多 1,000 个字符
我目前正在尝试计算每行字符和TXT文件的前1000个字符。我的代码计算文件的字符,并且没有产生任何错误,但不会以1,000的速度停止计数。我知道需要休息一下以解决这个问题,但我不知道我在做什么错。这是我的第一篇文章,如果我不太简洁或不够清晰,想提前道歉。
这使字符的值保持在1,000以上,但没有打印出来:
with open('myfile', 'r') as f:
characters = 0
for lines in f.readlines():
length = len(lines) - lines.count('\n')
characters += sum(len(length) for length in lines)
if characters >= 1000:
break
print('the number of characters in this line is: %s' % length)
print('the total number of characters is: %s' % characters)
这也使字符的值保持在1,000以上并打印出来:
with open('myfile', 'r') as f:
characters = 0
for lines in f.readlines():
length = len(lines) - lines.count('\n')
characters += sum(len(length) for length in lines)
print('the number of characters in this line is: %s' % length)
print('the total number of characters is: %s' % characters)
I am currently trying to count the characters per line and the first 1,000 characters of a txt file. My code counts the characters of the file and produces no error, but does not stop the count at 1,000. I know there needs to be a break to fix this problem, but I do not know what I'm doing wrong. This is my first post and would like to apologize in advance if I'm not being succinct or clear enough.
This keeps the values of characters at over 1,000 but does not print them:
with open('myfile', 'r') as f:
characters = 0
for lines in f.readlines():
length = len(lines) - lines.count('\n')
characters += sum(len(length) for length in lines)
if characters >= 1000:
break
print('the number of characters in this line is: %s' % length)
print('the total number of characters is: %s' % characters)
and this also keeps the values of characters at over 1,000 and prints them:
with open('myfile', 'r') as f:
characters = 0
for lines in f.readlines():
length = len(lines) - lines.count('\n')
characters += sum(len(length) for length in lines)
print('the number of characters in this line is: %s' % length)
print('the total number of characters is: %s' % characters)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)