这是我在Stack Overflow社区的第一篇文章。提前谢谢。
我有以下文本结构
name:Light
component_id:12
-------------------
name:Normallight
component_id:13
-------------------
name:Externallight
component_id:14
-------------------
name:Justalight
component_id:15
我想知道如何打印以";name";连同下一个以";component_id";因此,使用Python:看起来像这样
name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15
到目前为止,我有这个脚本,但它只打印以";name";
x = open("file.txt")
for line in x:
if line.startswith("name")
print(line)
感谢
一种方法是将整个文件作为字符串读取到Python中,然后使用正则表达式:
import re
with open('file.txt', 'r') as file:
lines = file.read()
matches = [x[0] + ',' + x[1] for x in re.findall(r'b(name:w+)s+(component_id:d+)', lines)]
print('n'.join(matches))
此打印:
name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15
使用一个变量怎么样?
x = open("file.txt")
found = None
for line in x:
if line.startswith("name"):
found = line
elif found is not None:
print(found + "," + line)
found = None
如果您的结构仅由三种类型的行组成,并且您知道以组件id开头的行在以名称开头的行之后,那么您可以尝试在名称出现时将其存储在变量中,然后在组件id行出现时打印整行。
例如:
for line in x:
if line.startswith("name"):
temp = line
if line.startswith("component_id"):
print(temp + ',' + line)