[英]error in retriving dictionary keys from file in python
關於SO也有類似的問題/答案,但這是指一個特定的錯誤,我已經參考了相關的SO主題來解決此問題,但是沒有運氣。
我想要的代碼旨在從文本文件中檢索行,並將其讀入字典中。 它可以工作,但是正如您在下面看到的那樣,並不完全。
文件
"['a', 5]"
"['b', 2]"
"['c', 3]"
"['d', 0]"
碼
def readfiletodict():
with open("testfile.txt","r",newline="") as f:
mydict={} #create a dictionary called mydict
for line in f:
(key,val) = line.split(",")
mydict[key]=val
print(mydict) #test
for keys in mydict:
print(keys) #test to see if the keys are being retrieved correctly
readfiletodict()
所需的輸出:
我希望字典中包含鍵 :a,b,c,d和文件中所示的相應值,而沒有多余的字符。 同樣,我需要將值正確地以整數形式存儲在字典中(以便以后可以使用它們)
要進行快速復制,請參閱: https : //repl.it/KgQe/0了解整個代碼和問題
當前(錯誤)輸出:
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
{'"[\'a\'': ' 5]"\r\n', '"[\'b\'': ' 2]"\r\n', '"[\'c\'': ' 3]"\r\n', '"[\'d\'': ' 0]"\r\n'}
"['a'
"['b'
"['c'
"['d'
我在當前代碼中使用的Stackoverflow答案來自: Python-文件到字典? 但這對我來說不太有效...
執行此操作的有效方法是使用@Tico建議的python列表。
但是,如果由於某種原因不能這樣做,可以嘗試一下。
lineFormat = re.sub('[^A-Za-z0-9,]+', '', line)
這將把"['a', 5]"
為a,5
。 現在,您可以應用拆分功能。
(key,val) = lineFormat.split(",") mydict[key]=val
您的代碼稍作修改-關鍵是刪除所有我們不關心的字符( [Python]:str.rstrip([chars]) ):
def readfiletodict():
with open("testfile.txt", "r") as f:
mydict = {} #create a dictionary called mydict
for line in f:
key, val = line.strip("\"\n[]").split(",")
mydict[key.strip("'")] = val.strip()
print(mydict) #test
for key in mydict:
print(key) #test to see if the keys are being retrieved correctly
readfiletodict()
輸出 :
(py35x64_test) c:\\Work\\Dev\\StackOverflow\\q46041167>python a.py {'d': '0', 'c': '3', 'a': '5', 'b': '2'} d c a b
如果在真正的python列表中轉換string_list,則要容易得多,因此不需要解析。 使用json加載:
import json
...
list_line = json.loads(line)
...
希望能幫助到你!
僅使用Python的非常基礎的知識:
>>> mydict = {}
>>> with open('temp.txt') as the_input:
... for line in the_input:
... values = line.replace('"', '').replace("'", '').replace(',', '').replace('[', '').replace(']', '').rstrip().split(' ')
... mydict[values[0]] = int(values[1])
...
>>> mydict
{'a': 5, 'b': 2, 'c': 3, 'd': 0}
換句話說,丟棄所有標點符號,僅在字典所需的兩個值之間留空白。 在空白處拆分,然后將拆分后的片段放入字典中。
編輯:以類似的方式使用正則表達式。 re.sub
查找其第一個參數給出的各種替代字符,找到的所有替換字符均由其第二個參數(空字符串)替換。 備選方案以“ |”分隔 正則表達式模式中的字符。 有些替代項,例如'[',必須用'\\'進行轉義,因為它們本身在正則表達式中具有特殊含義。
>>> mydict = {}
>>> with open('temp.txt') as the_input:
... for line in the_input:
... values = re.sub(r'"|\'|\,|\[|\]|,', '', line).split(' ')
... mydict[values[0]] = int(values[1])
...
>>> mydict
{'a': 5, 'b': 2, 'c': 3, 'd': 0}
您可以使用regex
和dict-comprehension來做到這一點:
#!/usr/bin/env python
import re
with open('file.txt', 'r') as f: l = f.read().splitlines()
d = {''.join(re.findall('[a-zA-Z]+',i)):int(''.join(re.findall('\d',i))) for i in l}
結果:
{'a': 5, 'c': 3, 'b': 2, 'd': 0}
您快到了,錯過了兩件事:
以下代碼滿足您的需求(我認為):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
output = dict()
with open('input', 'r') as inputfile:
for line in inputfile:
line = line.strip('"[]\n')
key, val = line.split(',')
output[key.strip("'")] = int(val)
但是請小心,因為此代碼非常脆弱。 它不會處理您正確提供的輸入格式的任何變化。 在此基礎上,我建議至少使用except ValueError
進行int轉換,並再次考慮剝離字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.