简体   繁体   English

如何创建由两条不同数据线的数据组成的 integer?

[英]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.

相关问题 如何用多行从2个不同的数据集中创建可视化? - How to create visualization from 2 different data sets with multiple lines? 如何从同一列中读取数据中的两行以创建该列中的值组合? - How to read two lines in a data from same column to create combination of values from that column? 如何从两个不同的列表中提取数据 - How to extract data from two different lists 如何从 python 中的文件中提取不同行的某些数据 - How to extract certain data on different lines from file in python 如何使用来自两个不同pandas数据帧的数据创建列散点图 - How to create a column scatter plot with data from two different pandas dataframes 如何创建一个从文本文件中读取数据并将其打印在两个不同部分的程序 - how to create a program that reads the data from the text file and prints it out in two different sections 如何从列表Python中的项目组成的整数中获取前导零 - how to get Leading Zeros in integer composed from items on a list Python 如何绘制来自两个不同数据集的数据 - How to plot data from two different data sets 如何基于两个不同数据帧的列创建新的df? - How to create new df based on columns of two different data frames? 由不同数据帧的唯一值组成的新数据帧 - New data frame composed of unique values of different dataframes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM