Regex Python 3。在搜索txt文件时--目标是同时获取标题和搜索的文本
关于我正在使用的以下代码的一个问题——工作非常完美,但希望在得到结果时获得更多信息Regex Python 3。在搜索txt文件时--目标是同时获取标题和搜索的文本,regex,python-3.x,search,Regex,Python 3.x,Search,关于我正在使用的以下代码的一个问题——工作非常完美,但希望在得到结果时获得更多信息 search_path = ('location of myfile.txt') file_type = ('myfile.txt') search_str = input("Enter the search string : ").strip() if not (search_path.endswith("/") or search_path.endswith("\\") ): searc
search_path = ('location of myfile.txt')
file_type = ('myfile.txt')
search_str = input("Enter the search string : ").strip()
if not (search_path.endswith("/") or search_path.endswith("\\") ):
search_path = search_path + "/"
if not os.path.exists(search_path):
search_path ="."
for fname in os.listdir(path=search_path):
# Apply file type filter
if fname.endswith(file_type):
# Open file for reading
fo = open(search_path + fname)
# Read the first line from the file
line = fo.readline()
# Initialize counter for line number
line_no = 1
# Search for string with lower case
index = line.find(search_lower)
if ( index != -1) :
print(fname, "[", line_no, ",", index, "] ", line, sep="")
# Read next line
line = fo.readline()
# Increment line counter
line_no += 1
# Close the files
fo.close()
================================
myfile.txt
/This is in the first one- - -1 : Color
Name Value
--------------- ---------------------------------------------------------------------------------------
Blue Car
Green Drive
Red Bike
/This is in the 2nd one- - -2 : Gears
Name Value
--------------- ---------------------------------------------------------------------------------------
Auto Car
Man Drive
None Bike
如果我搜索“自行车”
脚本给了我一行,但也希望在其列表中包含上面包含/的标题
再次感谢
Dan您可以记住最后一个标题:
last_head = ""
... # for all line in file:
if len(line) > 0 and line.startswith('/'):
last_head = line.strip()[1:]
if index != -1 :
print(fname, last_head, "[", line_no, ",", index, "] ", line, sep="")
我喜欢你的解决方案,但我建议使用
line.startswith(“/”)
使它更清晰易读。谢谢大家--我会检查一下,让你知道--它工作得很好,正是我想要的--再次感谢大家对这两个问题的快速响应