使用Python从.txt文件中的行获取值
我很难用python从.txt文件的一行中获取特定值。例如,从这一行: 包裹:发送=5,接收=7,丢失=0 我想得到整数值 我已经试着用下面的方法使用字典,通过字典分配键和值使用Python从.txt文件中的行获取值,python,Python,我很难用python从.txt文件的一行中获取特定值。例如,从这一行: 包裹:发送=5,接收=7,丢失=0 我想得到整数值 我已经试着用下面的方法使用字典,通过字典分配键和值 data = {} with open("file.txt", "rt", errors = "ignore") as file: lines = file.readlines() for line in line
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
data={}
打开(“file.txt”、“rt”、errors=“ignore”)作为文件:
对于文件中的行:
如果“包:”在同一行:
#删除行中的所有空格
行=行。替换(“,”)
#删除“包”:
行=行。拆分(“:”[1]
#把每一对分开
kv_线对=线分裂(“,”)
#查字典
对于kv_对中的kv:
键,值=千伏。拆分('='))
数据[键]=值
说你有电话
line='Packages:Sent=5,Received=7,Lost=0'
要清除行中的每个“单词”。拆分(=”
,您可以执行以下操作:
words=[word.strip(',:')用于line.split()中的单词
请注意,split()
(无参数)在空格上拆分。
如果您知道您需要例如元素3
(str
'5'
),请执行以下操作
val=单词[3]
您甚至可以通过以下方式将其转换为适当的int
val=int(单词[3])
当然,如果str
实际上并不表示整数,则此操作将失败
旁注
请注意,
line.split(“:”
本身没有任何效果,因为str
行
没有发生突变(str
在Python中从不发生突变)。这只是计算结果的列表,然后将其丢弃,因为您没有将此结果分配给变量。要检查变量是否为int,可以使用以下方法:
i=12
打印(isinstance(i,int))#真
i=“12”
打印(isinstance(i,int))#错误
在您的示例中,您只需要这样做:
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