gpt4 book ai didi

python - 我的代码只循环到某个点并忽略之后的 Python、字典

转载 作者:行者123 更新时间:2023-11-30 21:53:57 24 4
gpt4 key购买 nike

数据

slot : acu:1/1                         plannedtype : ngfcf                       actualtype : ngfcf                           operstatus : enabled              
errorstatus : noerror availability : available
alarmprofile : none capabprofile : not_applicable

slot : acu:1/2 plannedtype : ngfcf actualtype : ngfcf operstatus : enabled
errorstatus : noerror availability : available
alarmprofile : none capabprofile : not_applicable

slot : acu:1/3 plannedtype : ngfcf actualtype : ngfcf operstatus : enabled
errorstatus : noerror availability : available
alarmprofile : none capabprofile : not_applicable

As we can see the slot and other items are repeated, my loop is only inserting the first items in csv file i want to iterate through the repeated lines and add those values after":" to the next row of my csv file.


#reading a text file

import re
from collections import defaultdict
import pandas as pd

result = defaultdict(list)

with open('gthamelslot.txt') as f:
for line in f:
match = re.findall(r"\s+(\S+)\s+:\s+(\S+)", line)
for k,v in match:
if k in ["slot",
"errorstatus",
"alarmprofile",
"manufacturer",
"mnemonic",
"pbacode",
"fpbacode",
"fpbaics",
"cleicode",
"serialno",
"failedtest",
"ltrestarttime",
"plannedtype",
"ltrestartcause"]:
result[k].append(v)

df = pd.DataFrame(result)
writetocsv = df.to_csv("test.csv")
print(df)



Output i got

slot     plannedtype  actualtype  errorstatus
acu:1/1 ngfcf ngfcf noerror

output required

slot     plannedtype  actualtype  errorstatus
acu:1/1 ngfcf ngfcf noerror
acu:1/2 ngfcf ngfcf noerror
acu:1/3 ngfcf ngfcf noerror

最佳答案

以下更改:

将正则表达式更改为 r"\b(\S+)\s+:\s+(\S+)"以允许在行开头匹配(更改以查找字边界)

比较列表中的某些项目(例如“计划类型”)在文件中没有的情况下带有“-”(因此请删除所需字段中的“-”,例如计划类型、实际类型、错误状态)。

import re
from collections import defaultdict
import pandas as pd

result = defaultdict(list)

with open('gthamelslot.txt') as f:
for line in f:
match = re.findall(r"\b(\S+)\s+:\s+(\S+)", line)
for k,v in match:
if k in ["slot",
"actualtype",
"errorstatus",
"alarm-profile",
"manufacturer",
"mnemonic",
"pbacode",
"fpbacode",
"fpbaics",
"cleicode",
"serialno",
"failedtest",
"ltrestarttime",
"plannedtype",
"ltrestartcause"]:
result[k].append(v)

df = pd.DataFrame(result)
writetocsv = df.to_csv("test.csv")
print(df)

输出

slot plannedtype actualtype errorstatus
0 acu:1/1 ngfcf ngfcf noerror
1 acu:1/2 ngfcf ngfcf noerror
2 acu:1/3 ngfcf ngfcf noerror

关于python - 我的代码只循环到某个点并忽略之后的 Python、字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59479249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com