如何使用Python分隔值

时间:2019-08-21 11:57:57

标签: python dictionary import

如何使用Python分隔值?我已经尝试过splitlinespace,但它们并没有按照我期望的方式拆分数据

我的.txt文件包含以下内容:

{0: 'tench, Tinca tinca', 
1: 'goldfish, Carassius auratus', 
2: 'great white shark, white shark, man-eater, man-eating carcharias', 3: 'tiger shark, Galeocerdo cuvieri', 
4: 'hammerhead, hammerhead shark', 
5: 'electric ray, crampfish, numbfish, torpedo',} 

我正在寻找输出key = [0,1,2,3,...] Values = ['tench, Tinca tinca','goldfish, Carassius auratus',...],还是可以以某种方式将其转换为字典?我尝试使用参数(',')进行拆分,并且拆分了'tench,但我想将'tench,Tinca tinca'作为输出。

这是我坚持的代码

f = open('imagenet1000_clsid_to_human.txt', 'r') 
x = f.read().lower().strip().split("',") 
y = [] 
for i in x: (y.append(i)) 
    print(y)

4 个答案:

答案 0 :(得分:3)

关键思想是将原始文本读取为dict

import ast
with open('imagenet1000_clsid_to_human.txt', 'r') as f:
    s = f.read()
    dicts = ast.literal_eval(s)
print(list(dicts.keys()))
print(list(dicts.values()))

输出

[0, 1, 2, 3, 4, 5]
['tench, Tinca tinca', 'goldfish, Carassius auratus', 'great white shark, white shark, man-eater, man-eating carcharias', 'tiger shark, Galeocerdo cuvieri', 'hammerhead, hammerhead shark', 'electric ray, crampfish, numbfish, torpedo']

答案 1 :(得分:1)

肮脏的骇客:

a = re.findall("(\d+): \'(.*?)\'", txt)
keys, values = zip(*a)

其他肮脏的骇客:

txt = txt.replace("'", '"').replace(",}", "}")  
txt = re.sub("(\d+):", r'"\1":', txt)
data = json.loads(txt)

当然,您应该分别导入re或json。

答案 2 :(得分:1)

如果要将文本文件的str表示形式更改为dict,请使用:

str_to_dict = ast.literal_eval(x)

一旦有了字典,如果我理解正确的话,就需要所有键的1个列表和包含所有值的其他列表。为此,您可以这样做:

keys = []
values = []
for key,val in str_to_dict.items():
   keys.append(key)
   values.append(val)

答案 3 :(得分:1)

假设您可以将文件内容存储在str中:

text = "0: 'tench, Tinca tinca', 1: 'goldfish, Carassius auratus', 2: 'great white shark, white shark, man-eater, man-eating carcharias', 3: 'tiger shark, Galeocerdo cuvieri', 4: 'hammerhead, hammerhead shark', 5: 'electric ray, crampfish, numbfish, torpedo',"

text_list = list(filter(lambda x: len(x) > 0, text.split("',")))
keys = list(map(lambda x: x.split(":")[0], text_list))
values = list(map(lambda x: x.split(":")[1][2:], text_list))
my_dict = dict(zip(keys,values))

这不是最优雅的解决方案,但是如果您不想将其他软件包用作ast,则可以使用。但是,我建议您按照其他用户提供的答案中所述使用ast软件包,因为它可以处理不同的格式/间距,因此您不必为此担心。