簡體   English   中英

根據字符串從特定行讀取txt文件到特定行

[英]Read txt file from specific of line to a certain line base on string

我正在嘗試寫入一些 function 的數據,但是,我的數據是這樣的:

noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
...
coord sommets
0000 308 536
0001 472 386
0002 193 404

我想要的是在不知道行數但基於 txt 的字符串值的情況下從nom sommets訪問0004 Nice

讀取文本文件以列出基於關鍵字sommets的拆分

with open('text.txt') as file:
    lines = [line.rstrip() for line in file]

test_loop = []
for item in lines:
    if 'sommets' in item: 
        test_loop.append([item])
    else:  
        test_loop[-1].append(item)
print(test_loop)

它給出list of lists #的列表。

[['noms sommets', '0000 Abbesses', '0001 Alexandre Dumas', '0002 Paris', '0004 Nice', '...'], ['coord sommets', '0000 308 536', '0001 472 386', '0002 193 404']]

如果你想訪問第一個設置然后。

for sublist in test_loop[0]:
    print(sublist)

給#

noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
...

我們可以將整個 txt 文件作為單個字符串讀取,然后使用正則表達式來匹配關鍵字。

re.DOTALL修飾符將使'.' 匹配任何字符,包括換行符

with open('text.txt') as f:
  txt = f.read()

match = re.search('noms sommets.*?0004 Nice', a, re.DOTALL).group()
# match = 'noms sommets\n0000 Abbesses\n0001 Alexandre Dumas\n0002 Paris\n0004 Nice'

然后,您可以使用 match 作為變量或將其拆分為列表

>>> print(match)
noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
>>>

暫無
暫無

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

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