簡體   English   中英

如何使用Python結合正則表達式和字符串/文件操作並存儲模式的實例來搜索文本文件中的模式?

[英]How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

所以基本上我正在尋找文本文件中兩個尖括號內的4位數代碼。 我知道我需要打開文本文件然后逐行解析,但我不確定在檢查“for line in file”之后構建代碼的最佳方法。

我想我可以以某種方式拆分它,剝離它或分區,但我也編寫了一個我使用編譯的正則表達式,所以如果它返回一個匹配對象,我不認為我可以使用那些基於字符串的操作。 另外我不確定我的正則表達式是否足夠貪婪......

我想將所有找到的匹配的實例存儲為元組或列表中的字符串。

這是我的正則表達式:

regex = re.compile("(<(\d{4,5})>)?")

考慮到目前為止相當基本的代碼,我認為我不需要包含所有代碼。

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

關於正則表達式的幾個注釋:

  • 你不需要? 在結尾和外部(...)如果你不想將數字與尖括號匹配,但只想要數字本身
  • 它匹配尖括號之間的4或5位數

更新:重要的是要理解正則表達式中的匹配捕獲可能完全不同。 我上面的代碼段中的正則表達式使用尖括號匹配模式,但我要求僅捕獲內部數字, 而不使用尖括號。

關於python中的正則表達式的更多信息可以在這里找到: Regular Expression HOWTO

一次性閱讀:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

逐行:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

但同樣,除非您添加了偏移計數器,否則返回的匹配對除計數之外的任何內容都沒有用:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

但是,立即讀取整個文件仍然更有意義。

暫無
暫無

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

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