我有一个输入文件,我正在尝试从中建立数据库。
每行如下:
Amy Shchumer, Trainwreck, I Feel Pretty, Snatched, Inside Amy Shchumer
Bill Hader,Inside Out, Trainwreck, Tropic Thunder
以此类推。
第一个字符串是一个演员\女演员,然后是他们播放的电影。
数据未排序,它们是一些尾随空格。
我想创建一个看起来像这样的字典:
{'Trainwreck': {'Amy Shchumer', 'Bill Hader'}}
关键是电影,值应该是电影中的演员,并统一设置为一组数据类型。
def create_db():
my_dict = {}
raw_data = open('database.txt','r+')
for line in raw_data:
lst1 = line.split(",") //to split by the commas
len_row = len(lst1)
lst2 = list(lst1)
for j in range(1,len_row):
my_dict[lst2[j]] = set([lst2[0]])
print(my_dict)
这是行不通的...无法解决以下问题:当键已存在时,应将角色与上一个actor统一在一个集合中
相反,我最终得到了:
'Trainwreck': {'Amy Shchumer'}, 'Inside Out': {'Bill Hader'}
答案 0 :(得分:2)
`
import {Component, OnInit} from '@angular/core';
import {MenuItem} from "primeng/primeng";
import {DialogService} from 'primeng/api';
import {SelectItem} from 'primeng/api';
@Component({
selector: 'ivp-data-view',
templateUrl: './data-view.html',
styleUrls: ['./data-view.css'],
providers: [DatamartService,DialogService]
})
export class DataViewComponent implements OnInit {
items: MenuItem[];
profileName: string
display : boolean;
cars: SelectItem[]
sourceCars: SelectItem[];
constructor( private dmService: DatamartService,public dialogService:
DialogService ) {
this.sourceCars = [
{label: 'Audi', value: 'Audi'},
{label: 'BMW', value: 'BMW'},
{label: 'Fiat', value: 'Fiat'},
{label: 'Ford', value: 'Ford'},
{label: 'Honda', value: 'Honda'},
{label: 'Jaguar', value: 'Jaguar'},
{label: 'Mercedes', value: 'Mercedes'},
{label: 'Renault', value: 'Renault'},
{label: 'VW', value: 'VW'},
{label: 'Volvo', value: 'Volvo'}
];
}
public ngOnInit() {
this.items = [{
label: 'Explorer',
items: [
{label: 'Details', icon: 'pi pi-fw pi-plus'}
]
}];
}
`
}
输出:
def create_db():
db = {}
with open("database.txt") as data:
for line in data.readlines():
person, *movies = line.split(",")
for m in movies:
m = m.strip()
db[m] = db.get(m, []) + [person]
return db
这将循环遍历数据,并将每行的第一个值分配给{'Trainwreck': ['Amy Shchumer', 'Bill Hader'],
'I Feel Pretty': ['Amy Shchumer'],
'Snatched': ['Amy Shchumer'],
'Inside Amy Shchumer': ['Amy Shchumer'],
'Inside Out': ['Bill Hader'],
'Tropic Thunder': ['Bill Hader']}
,其余的分配给person
(有关movies
如何解压缩的示例,请参见here元组)。然后,对于所有电影,它使用.get来检查它是否在数据库中,如果返回则返回列表,如果不返回则返回一个空列表。然后将新演员添加到列表中。
另一种方法是使用defaultdict:
*
如果密钥不存在,它将自动分配from collections import defaultdict
def create_db():
db = defaultdict(lambda: [])
with open("database.txt") as data:
for line in data.readlines():
person, *movies = line.split(",")
for m in movies:
db[m.strip()].append(person)
return db
。