簡體   English   中英

在Python中查找文本文件中的子字符串

[英]Find a substring within a textfile in Python

所以我試圖在Python中的文本文件中提取一個鏈接 - 這個鏈接從textfile到textfile不等,但格式相同。 我嘗試使用re庫但不斷出錯。

鏈接的語法是:

docs.com/searchres.aspx?docformat=all&docid=[SOME NUMBER] - 

因此,鏈接的末尾在SOME NUMBER字段中有一個指定的編號,在鏈接的末尾有一個' - '如何從文本文件中搜索,查找和保存此鏈接。 謝謝 - 這是我第一次在SO上發帖

這是一個使用內存映射的Python解決方案。 一些警告:

  1. 你說文件中只有一個實例,如果有多個實例,它將返回第一個實例。
  2. 我從一些舊代碼中快速地將它放在一起。 如果]不在文本文件中,它將繼續讀取。 請查看此處mmap文檔,了解如何修改代碼以使其更加健壯。

編輯:Python的代碼格式化程序討厭我,所以我不得不做一些小的改動,以使其正確阻止。 對於那個很抱歉。

match = open(db, 'r')
try:
    search = mmap.mmap(match.fileno(), 0, access=mmap.ACCESS_READ)
    index = search.find(str(target))
    if index != -1:
        #"This entry exists. We have the index of it, now read the line."
        search.seek(index)
        #"Seek to the index."
        strOut = ""
        read = search.read(1)
        while read != ']':
            strOut = strOut + read
            read = search.read(1)
        search.close()
        match.close()

        print strOut
    else:
        #-1 indicates it's not in the file
        print strOut
except Exception as err:
    match.close()
    print strOut

所以這個響應很簡單,但適用於小文件。 當你說“保存此鏈接”時,我假設在字符串變量中使用url就足夠了。

import re

f = open(filename_str, 'r')
file_content = f.read()
p = re.compile('docs.com(.)*\-')
m = p.search(file_content)
if m != None:
    link = m.group(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM