如何使用Python分离值

2024-05-14 03:14:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用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)

Tags: 数据txt方式splitwhitemangoldfishshark
3条回答

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

str_to_dict = ast.literal_eval(x)

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

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

肮脏的黑客:

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。你知道吗

关键思想是将原始文本读作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']

相关问题 更多 >