我正在编写代码,查看文本文件中是否存在输入内容。
例如:
我输入“披萨”
我的文本文件包含:
bread
pizza
pasta
tomato
有没有办法打印出单词“pizza”所在的行号?
有两种方法可以实现这个:
对于第一种方法,首先读取每一行,然后获取单词所在的索引:
with open('path.txt') as f: data = f.readlines()
line_no = data.index("pizza")
或者,通过文件查找索引:
with open('path.txt') as f:
for line_no, line in enumerate(f):
if line == "pizza":
break
else: # for loop ended => line not found
line_no = -1
with open('test.txt') as f:
content = f.readlines()
index = [x for x in range(len(content)) if 'pizza' in content[x].lower()]
代码的第一部分将每行作为单独的列表读入到变量“content”中。
第二部分仅在某行存在“pizza”时才填充内容的行号。[x for x in range(len(content))]只是填充所有索引值,而“if 'pizza' in content[x].lower()”则保留与字符串匹配的行号。
import re
import os # You can go without is if you have other means to get your filepath
i = 1
matches = []
target = raw_input("Please type string to match\n")
with open(os.getenv("SOME_PATH") + "/myfile.txt") as fic: # open("myfile.txt") if in your current directory
for line in fic:
if re.search(target, line):
print "Found at line {}".format(i)
matches.append(i)
i = i +1
if not len(matches):
raise Exception, "target not found"
matches
将包含与输入模式匹配的所有行的索引。print next (i for i,v in enumerate (open (fname),1) if v == needle)