![](/img/trans.png)
[英]How to read specific characters from lines in a text file using 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.