3 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
如果您需要知道X出現(xiàn)的行號(hào):
target = 'X'
counter = 0
with open('testing.txt') as f:
for i, line in enumerate(f):
if target in line:
counter += 1
print('target is present in line {}'.format(
i+1))
print('target appears in {} lines'.format(counter))
如果您還需要知道X出現(xiàn)的列號(hào):
target = 'X'
counter = 0
with open('testing.txt') as f:
for i, line in enumerate(f):
for j, char in enumerate(line):
if target == char:
counter += 1
print('target is present in line {} at column {}'.format(
i+1, j+1))
print('target appears {} times'.format(counter))
一些澄清:
with ... open
完成后自動(dòng)關(guān)閉文件,因此您無需記住顯式關(guān)閉它for i, line in enumerate(f):
逐行迭代,而不將它們一次性全部加載到內(nèi)存中。

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
由于readlines()是一個(gè)列表,您需要迭代并簽入行。也許您可以用于for else此目的:
file = "testing.txt"
file = open(file, "r")
lines = file.readlines()
# char in the list
for line in lines:
if "X" in line:
print('X is present in the list')
break
else:
print('X is not present in the list')
它迭代每一行,如果任何行有字符,則break僅else在任何行中都找不到字符時(shí)才運(yùn)行。
更新
如果你想計(jì)數(shù),那么你可以簡(jiǎn)單地在循環(huán)中增加計(jì)數(shù)器,一旦循環(huán)完成檢查計(jì)數(shù)器:
file = "testing.txt"
file = open(file, "r")
lines = file.readlines()
# char in the list
counter = 0
for line in lines:
if "X" in line:
counter += 1 # < -- count
if counter: # check
print('X is present in the list')
else:
print('X is not present in the list')

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
正如您所要求的,我將輸出一個(gè)包含 item 的列表Yes, there are 3 X's。
我有我的dataf.txt文件:
XXX X XX X XX
X ASD X F FFFF XX
D X XXX X EFX
A F G
將數(shù)據(jù)讀入文件并計(jì)算 X 的數(shù)量(注意:我使用了列表理解 hack?。?/p>
with open('dataf.txt','r') as fl:
data = fl.readlines()
a = ['Yes, there are '+str(i.count('X')) + " X's" if 'X' in i else "No X's" for i in data]
print(a)
輸出:
["Yes, there are 9 X's", "Yes, there are 4 X's", "Yes, there are 6 X's", "No X's"]
添加回答
舉報(bào)