繁体   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