如果一行以字符串开头,则打印该行和下一行
If a line starts with a string print THAT line and THE FOLLOWING one
这是我在 Stack Overflow community.Thanks 中的第一个 post 提前。
我有以下文本结构
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)
谢谢
使用变量如何?
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
如果你的结构只是由三种类型的行组成,并且你知道以component id开头的行在以name开头的行之后,那么你可以尝试在出现name时将它存储在一个变量中然后在组件 id 行出现时打印整行。
例如:
for line in x:
if line.startswith("name"):
temp = line
if line.startswith("component_id"):
print(temp + ',' + 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
这是我在 Stack Overflow community.Thanks 中的第一个 post 提前。
我有以下文本结构
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)
谢谢
使用变量如何?
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
如果你的结构只是由三种类型的行组成,并且你知道以component id开头的行在以name开头的行之后,那么你可以尝试在出现name时将它存储在一个变量中然后在组件 id 行出现时打印整行。
例如:
for line in x:
if line.startswith("name"):
temp = line
if line.startswith("component_id"):
print(temp + ',' + 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