档案test1.log
:
{'Python' : '.py', 'C++' : '.cpp', 'length' : 24}
def validate_file(f):
#print('File Header Validation:')
fname=open(f)
count=0
for line in fname:
if 'length' in line:
print(line['length'])
validate_file("test1.log")
我正在尝试找到length
的值?在从文件test1.log
读取文本后,输出是这里的输出:
print(line['length'])
TypeError: string indices must be integers
任何帮助我如何提取'长度'场?
答案 0 :(得分:1)
您可以使用ast.literal_eval()
来执行此操作:
def validate_file(f):
with open(f) as contents:
for line in contents:
data = ast.literal_eval(line)
if 'length' in data:
print(data['length'])
import ast
validate_file("test1.log")
24
答案 1 :(得分:0)
首先将字符串转换为JSON。
lst <- split(df1, df1$ID)
df2 <- do.call(rbind, lst[sample(names(lst))])
row.names(df2) <- NULL
df2
# ID percent region
#1 4 1 1
#2 4 1 2
#3 4 8 3
#4 3 9 1
#5 3 78 2
#6 3 56 3
#7 3 99 4
#8 2 20 1
#9 2 6 2
#10 2 9 3
#11 2 1 4
#12 1 5 1
#13 1 8 2
#14 1 10 3
#15 1 100 4
答案 2 :(得分:0)
你访问错误的方式,你拥有的行是dict格式,所以在json中加载单独的并使用get方法访问密钥
双引号中的test1.log 值
{"Python" : ".py", "C++" : ".cpp", "length" : 24}
def validate_file(f):
#print('File Header Validation:')
fname=open(f)
count=0
for line in fname:
line=json.loads(line)
print(line.get("length",""))#if length not then nothing print