【问题标题】:Python 3 . When searching txt file - -aim to also get title as well as searched text蟒蛇 3 。搜索 txt 文件时 - 旨在获取标题以及搜索到的文本
【发布时间】:2016-10-21 12:28:24
【问题描述】:

只是关于我正在使用的以下代码的一个问题——效果很好,但希望在获得结果时获得更多信息

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

如果我搜索“自行车”

脚本给了我一行,但也想在上面包含标题,其中包含 / 在其列表中

再次感谢

【问题讨论】:

    标签: regex python-3.x search


    【解决方案1】:

    你可以记住最后一个标题:

    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('/') 使其更清晰易读。
    • 谢谢大家 - - 会检查出来
    • 只是为了让您知道--效果很好,正是我想要的--再次感谢您对两者的快速响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2017-04-13
    • 2017-08-15
    • 1970-01-01
    • 2022-11-28
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多