计算文件的最多 1,000 个字符

发布于 2025-01-18 05:31:03 字数 948 浏览 5 评论 0原文

我目前正在尝试计算每行字符和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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞄了个咪的 2025-01-25 05:31:03
   with open('myfile', 'r') as f:
   ch = 0
   for line in f.readlines():
       length = len(line)
       ch = ch + len(line)
       print('the number of characters in this line is: %d' % length)
       if ch >= 1000:
           break
   f.close()
   with open('myfile', 'r') as f:
   ch = 0
   for line in f.readlines():
       length = len(line)
       ch = ch + len(line)
       print('the number of characters in this line is: %d' % length)
       if ch >= 1000:
           break
   f.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文