[英]extracting the line with a string from a file using python
球隊,
我想使用一個字符串(以tg_開頭)從文件中提取一些行,並根據以下正則表達式獲取輸出。.問題是,
我不確定如果2行以\\
結尾,如下所示,該如何提取行。
我不知道如何使用正則表達式下面的以下內容刪除特殊字符。
*****來自文件*******
tg_cr_counters dghbvcvgfv
tg_kk_bb a group1再見再見嗨嗨1 \\ <<<<
修補程序mac hdfh f dgf asadasf \\
dgfgmnhnjgfgtg_cr_counters gthghtrhgh}}] <<<<<
tg_cr_counters fkgnfkmngvd
import re
file = open("C:\\Users\\input.tcl", "r")
f1 = file.readlines()
output = open("extract.txt", "a+")
match_list = [ ]
for item in f1:
match_list = re.findall(r'[t][g][_]+\w+.*', item)
if(len(match_list)>0):
output.write(match_list[0]+"\r\n")
print(match_list)
您可以將regex與標志一起用於re.MULTILINE和re.DOTALL 。
這樣一來.
也會匹配\\n
,您可以查找以tg_
(無需將每個都放在[]
)和以雙\\n\\n
(或文本結尾) \\Z
結尾的任何內容:
fn = "t.txt"
with open (fn,"w") as f:
f.write("""*****from a file*******
tg_cr_counters dghbvcvgfv
tg_kk_bb a group1 bye bye bye hi hi hi 1 \ <<<<
patch mac hdfh f dgf asadasf \
dgfgmnhnjgfg
tg_cr_counters gthghtrhgh }} ] <<<<<
tg_cr_counters fkgnfkmngvd
""")
import re
with open("extract.txt", "a+") as o, open(fn) as f:
for m in re.findall(r'^tg_.*?(?:\n\n|\Z)', f.read(), flags=re.M|re.S):
o.write("-"*40+"\r\n")
o.write(m)
o.write("-"*40+"\r\n")
with open("extract.txt")as f:
print(f.read())
輸出(每次匹配都在----------------------------------------
的一行之間) :
----------------------------------------
tg_cr_counters dghbvcvgfv
----------------------------------------
----------------------------------------
tg_kk_bb a group1 bye bye bye hi hi hi 1 \ <<<<
patch mac hdfh f dgf asadasf dgfgmnhnjgfg
----------------------------------------
----------------------------------------
tg_cr_counters gthghtrhgh }} ] <<<<<
----------------------------------------
----------------------------------------
tg_cr_counters fkgnfkmngvd
----------------------------------------
re.findall()
結果如下:
['tg_cr_counters dghbvcvgfv\n\n',
'tg_kk_bb a group1 bye bye bye hi hi hi 1 \\ <<<<\npatch mac hdfh f dgf asadasf dgfgmnhnjgfg\n\n',
'tg_cr_counters gthghtrhgh }} ] <<<<<\n\n',
'tg_cr_counters fkgnfkmngvd\n']
要啟用多行搜索,您需要一次讀入多行內容-如果文件太小,則會導致內存問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.