【问题标题】:How to NOT count the characters in lines that start with '#' in a text file with python如何在使用python的文本文件中不计算以'#'开头的行中的字符
【发布时间】:2017-02-13 14:44:54
【问题描述】:

我有这段代码可以读取文本文件中的行并计算字符数,一旦达到 1000 个字符或更多字符就会停止。如何修改它,使其不计算任何以 # 符号开头的行上的字符?

infile = open('word_count.tst', 'r') #word_count is just a sample file.
lines = infile.readlines()
char_count = 0
for line in lines:
    char_count = char_count + len(line)
    if char_count >= 1000:
        break
print("File has %d characters" % (char_count))

【问题讨论】:

  • 添加一个钩子检查是否line.startswith('#')

标签: python


【解决方案1】:

使用with 语句打开文件。不要读取所有行,只需遍历文件对象。使用a = a + b 的简写为a += b。检查行是否以#string.startswith() 函数开头并用not 取反以获得所需的条件。

你可以这样做:

char_count = 0
with open('word_count.tst', 'r') as f:
    for l in f:
        if not l.startswith('#'):
            char_count += len(l)
            if char_count >= 1000:
                break

【讨论】:

    【解决方案2】:

    只需在代码中添加if line[0] != "#":

    f = open('word_count.txt', 'r') #word_count is just a sample file.
    char_count = 0
    for line in f:
        if line[0] != "#":
            char_count = char_count + len(line)
            if char_count >= 1000:
                break
    print("File has %d characters" % (char_count))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2017-01-27
      相关资源
      最近更新 更多