在列表中查找字符索引

我想在 .txt 文件中搜索某个字符 (X),如果存在,则执行某个操作。不幸的是这段代码不起作用:


file = "test.txt"

file = open(file, "r") 

lines = file.readlines()



# char in the list

if "X" in lines:

    print('X is present in the list')


# char not in the list

if "X" not in lines:

    print('X is not present in the list')

测试.txt 文件:


XX X XXX X XX

XXXXX XX X    XX

有什么想法吗?


PS:即使将“X”更改为“X”也不起作用。


陪伴而非守候
浏览 216回答 3
3回答

MM们

如果您需要知道X出现的行号:target = 'X'counter = 0with 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出现的列号:target = 'X'counter = 0with 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完成后自动关闭文件,因此您无需记住显式关闭它for i, line in enumerate(f):逐行迭代,而不将它们一次性全部加载到内存中。

PIPIONE

由于readlines()是一个列表,您需要迭代并签入行。也许您可以用于for else此目的:file = "testing.txt"file = open(file, "r")&nbsp;lines = file.readlines()# char in the listfor line in lines:&nbsp; &nbsp; if "X" in line:&nbsp; &nbsp; &nbsp; &nbsp; print('X is present in the list')&nbsp; &nbsp; &nbsp; &nbsp; breakelse:&nbsp; &nbsp; print('X is not present in the list')它迭代每一行,如果任何行有字符,则break仅else在任何行中都找不到字符时才运行。更新如果你想计数,那么你可以简单地在循环中增加计数器,一旦循环完成检查计数器:file = "testing.txt"file = open(file, "r")&nbsp;lines = file.readlines()# char in the listcounter = 0for line in lines:&nbsp; &nbsp; if "X" in line:&nbsp; &nbsp; &nbsp; &nbsp; counter += 1&nbsp; # < -- count&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if counter: # check&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; print('X is present in the list')&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;else:&nbsp; &nbsp; print('X is not present in the list')&nbsp;

ibeautiful

正如您所要求的,我将输出一个包含 item 的列表Yes, there are 3 X's。我有我的dataf.txt文件:XXX X XX X XXX ASD X F FFFF XXD X XXX X EFXA F G将数据读入文件并计算 X 的数量(注意:我使用了列表理解 hack!)with open('dataf.txt','r') as fl:&nbsp; &nbsp; data = fl.readlines()&nbsp; &nbsp; a = ['Yes, there are '+str(i.count('X')) + " X's" if 'X' in i else "No X's" for i in data]&nbsp; &nbsp; print(a)输出:["Yes, there are 9 X's", "Yes, there are 4 X's", "Yes, there are 6 X's", "No X's"]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python