繁体   English   中英

使用 Python 从 .txt 文件中的一行获取值

[英]Getting values from a line in a .txt file with Python

我很难用 python 从 .txt 文件的一行中获取特定值。 例如从这一行:

包裹:发送 = 5,收到 = 7,丢失 = 0

我想获得整数值。

我已经尝试通过尝试使用字典分配键和值来以以下方式使用字典。

data = {} 
with open("file.txt", "rt", errors = "ignore") as file:                
    lines = file.readlines()
    for line in lines:
        if "Packages:" in line:
            line.split(":")
            key1, value1, key2, value2, key3, value3 = line.split(" = ")
            data[key1, key2, key3] = value1, value2, value3
            print(value1, value2, value3)

我是初学者,所以如果这个问题微不足道,请原谅。

谢谢!

您必须将分割线分配给 th 变量

data = {} 
with open("file.txt", "rt", errors = "ignore") as file:                
    lines = file.readlines()
    for line in lines:
        if "Packages:" in line:
            line = line.strip().split(":")
            key1, value1, key2, value2, key3, value3 = line.split(" = ")
            data[key1, key2, key3] = value1, value2, value3
            print(value1, value2, value3)

您走在正确的轨道上,只是实施中存在一些问题:

data = {} 
with open("file.txt", "rt", errors = "ignore") as file:                
    for line in file:
        if "Packages:" in line:
            # Remove all spaces in line
            line = line.replace(" ", "")

            # Remove "Packages:" 
            line = line.split(":")[1]

            # Separate out each <key, value> pair
            kv_pairs = line.split(",")
           
            # Fill the dictionary
            for kv in kv_pairs:
                key, value = kv.split('=')
                data[key] = value

说你有这条线

line = 'Packages: Sent = 5, Received = 7, Lost = 0'

要清理line.split(" = ")每个“单词”,您可以执行例如

words = [word.strip(' ,:') for word in line.split()]

请注意split() (不带参数)在空白处拆分。 如果您知道您想要例如元素3str '5' ),请执行

val = words[3]

您甚至可以通过以下方式将其转换为适当的int

val = int(words[3])

当然,如果str实际上不代表整数,这将失败。

边注

请注意, line.split(":")本身没有任何效果,因为str line没有发生变异( str在 Python 中永远不会发生变异)。 这只是计算结果list ,然后将其丢弃,因为您没有将此结果分配给变量。

检查 var 是否为 int 你可以使用这个:

i = 12 打印(isinstance(i,int))#True

i = "12" print(isinstance(i, int)) #False

在你的例子中,你只需要这样做:

lines = ["Packages: Sent = 5, Received = 7, Lost = 0"]
data = {}
linenumber = 1
for line in lines:
    
    line = line.split(": ")[1]
    col = line.split(",")
    dic = {}
    for item in col:
        item = item.split(" = ")
        dic.update({item[0]:item[1]})
    data.update({"1":dic})

    linenumber += 1
    
print(data)

如果您只需要检查整数值,您应该这样做:

lines = ["Packages: Sent = 5, Received = oi, Lost = 0"]
data = {}
error=[]
linenumber = 1
for line in lines:
    
    line = line.split(": ")[1]
    col = line.split(",")
    dic = {}
    for item in col:
        item = item.split(" = ")
        try:
            if isinstance(int(item[1]), int):
                dic.update({item[0]:item[1]})
        except:
            error.add("Cannot convert str to int in line " + linenumber )
            # nothing to do
    data.update({"1":dic})

    linenumber += 1
    
print(data)
data = {}
with open("file.txt", "rt", errors = "ignore") as file:
     lines = file.readlines()
     for line in lines:
         if "Packages:" in line:
             line_vals=line.replace('Packages:', '').replace('\n','').split(',')
             for j in line_vals:
                 vals=j.split('=') # here you can get each key and value as pair
                 key=vals[0] #here is your key
                 value =vals[1] # here is your value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM