簡體   English   中英

python - 如何不計算文本文件中以“#”開頭的行中的字符

[英]How to NOT count the characters in lines that start with '#' in a text file with python

我有這段代碼可以讀取文本文件中的行並計算字符數並在達到 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))

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

只需將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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM