我是菜鸟,所以我希望这是问这个问题的正确地方。这真让我发疯。我正在某些文本文件中寻找句子,这是部分代码:
SentenceIMLookingfor='blha blha blah'
with open('textfile.lua','r') as my_file:
raw_dadat=my_file.read().split('\n')
for i in range(1, len(raw_dadat)):
if(raw_dadat[i]==SentenceIMLookingfor):
DO_SOMETHING
Run Code Online (Sandbox Code Playgroud)
好吧,它什么也没做。(而且我需要知道“ SentenceIMLookingfor”在哪一行)。我已经检查了ID(ofc它们是不同的,所以如果我使用“ is”而不是“ ==”,则将无法使用)。另外,我确定该句子在我的文本文件中,甚至存储在raw_data [210]中。我检查了“类型”,它是str。句子中也有大约3个空格,我不知道这是否有帮助,并且“ len(raw_dadat)”或多或少等于4000。那么我看不出我在做什么错。在此先多谢!!
多余的空间可能是您的罪魁祸首。您也可以尝试将字符串缩小写。
SentenceIMLookingfor='blha blha blah'
with open('textfile.lua','r') as my_file:
for line in my_file:
if line.lower().strip() == SentenceIMLookingfor:
#DO_SOMETHING
Run Code Online (Sandbox Code Playgroud)
但是,如果您没有检查与您要查找的句子完全相等的行,则需要使用in运算符检查是否相等,因此将if上面的内容替换为
if SentenceIMLookingfor in line.lower(): # you may not want .lower()
Run Code Online (Sandbox Code Playgroud)
由于不需要将整个文件读入内存,因此可以使用来遍历文件的各行for line in my_file。 .lower()将字符串转换为所有小写字母,.strip()并截断所有前面或结尾的空格
如@SethMMorton在评论中所建议,您可以使用enumerate来迭代行号for i, line in enumerate(my_file)
如果您尝试收集此字符串出现的行号(似乎可能),则可以通过列表理解来完成
with open('textfile.lua','r') as my_file:
line_nos = [i for i, line in enumerate(my_file) if line.lower().strip() == SentenceIMLookingfor]
Run Code Online (Sandbox Code Playgroud)