【发布时间】:2018-05-03 07:13:10
【问题描述】:
我有一个由几个部分组成的文本文件。部分总是以非空格开头。小节总是以空格开头。基于 input.txt,以下是我的预期结果。在这个例子中,我试图搜索“101”,如果 101 出现在部分或小节中。我想显示带有小节的部分。我正在尝试解析该部分并存储在动态变量中。但我不确定如何将部分动态存储在变量中。
输入.txt
test1 text101
aaa
bbb
ccc
test2 text101
aaa
bbb
ccc
ddd 101
test3 text101 - 123
test4 text123
aaa
bbb
ccc
ddd 101
test5 text456
aaa
bbb
ccc
test6 101
qqq
ppp
test7 text101 - 123
test8 text102 - 123
Test9 text101 - 123
Test10 text102 - 123
Python 3.0 代码:
find_txt = '101'
result = []
f = open(r'\\input.txt')
for line in f:
if (line[:1]!=' '):
result.append(line)
print ('Result:')
for element in result:
if find_txt in element:
print (element, end='')
输出:
test1 text101
aaa
bbb
ccc
test2 text101
aaa
bbb
ccc
ddd 101
test3 text101 - 123
test4 text123
aaa
bbb
ccc
ddd 101
test6 101
qqq
ppp
test7 text101 - 123
Test9 text101 - 123
【问题讨论】:
-
而不是将其存储在“动态变量”中,而是将其存储在字典中!
标签: python regex python-3.x search find