[英]How to create an integer composed of data from two different data lines?
I am trying to define the variable ini_f in my code below as the last three characters of the line with 'CAFE' being the most significant digits and the second, third, and forth characters of the line following the CAFE line to be the three least significant digits.我试图在下面的代码中将变量 ini_f 定义为该行的最后三个字符,其中“CAFE”是最高有效数字,CAFE 行之后的行的第二、第三和第四个字符是最少的三个有效数字。
with open('data.txt', "r") as dataset:
for line in dataset:
if 'CAFE' in line:
ini_f = line[5:], line+1[1:4]
print(ini_f)
else:
pass
You can keep track if you found 'CAFE' in a line with the help of a true/false variable.如果您在真/假变量的帮助下在一行中找到“CAFE”,您可以跟踪。 If you did not find 'CAFE' in a line, you can set it back to false.
如果您没有在一行中找到“CAFE”,您可以将其设置回 false。 This is the example code:
这是示例代码:
with open('data.txt', 'r') as dataset:
ini_f = ''
found_cafe = False
for line in dataset:
if found_cafe:
ini_f += line[-4:-1]
print(ini_f)
if 'CAFE' in line:
ini_f = line[:3]
found_cafe = True
else:
found_cafe = False
ini_f = ''
I used this file to test the functionality:我用这个文件来测试功能:
Loremipsumdolorsitamet
conseteturCAFEsadipscingelitr
seddiamnonumyeirmodtempor
inviduntutlaboreetdolore
magnaaliquyameratseddiamvoluptua
AtveroCAFEeosetaccusametjusto
duodoloreseCAFEtearebum
Stetclitakasdgubergren
noseatakimatasanctus
Giving this output:给出这个 output:
conpor
Atvbum
duoren
We extract the first three digits with line[:3] and the last 3 readable digits with line[-4:-1], because the last digit is a newline (\n).我们用 line[:3] 提取前三个数字,用 line[-4:-1] 提取最后 3 个可读数字,因为最后一个数字是换行符 (\n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.