从文本fi创建python词典

2024-09-27 04:21:38 发布

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

我有一个文本文件如下所示:

01:Pronoun
02:I
03:We
04:Self
05:You
06:Other
07:Negate
08:Assent
09:Article
10:Preps
11:Number
12:Affect
...

现在我想编一本字典。。这样的字典:

^{pr2}$

这是我到目前为止得到的代码,但它似乎不能像我想要的那样工作。。。在

with open ('LIWC_categories.text','rU') as document1:
    categoriesLIWC = {}
    for line in document1:
        line = line.split()
        if not line:
            continue
        categoriesLIWC[line[0]] = line[1:]

Tags: selfyounumber字典linearticleweother
3条回答

如果不希望包含冒号,可以在冒号上拆分以获取键和值

key, value = line.split(':')

需要向split()传递分隔符字符串。在这种情况下,它将是“:”。在

在拆分.string()将在空白处自动拆分,但您的行中没有空格。如果要在键中使用:键,则可以始终将其与

categoriesLIWC[line[0] + ":"] = line[1]

还有

^{pr2}$

应该是

line[1]
In [27]: dic={}

In [28]: with open("abc.txt") as f:
    for line in f:
        if line.strip():                 #if line is not empty
            k,v=line.split(":")          #split at ":" not at whitespaces
            dic[k]=[v.strip()]           #add to dict
   ....:             

In [29]: dic
Out[29]: 
{'01': ['Pronoun'],
 '02': ['I'],
 '03': ['We'],
 '04': ['Self'],
 '05': ['You'],
 '06': ['Other'],
 '07': ['Negate'],
 '08': ['Assent'],
 '09': ['Article'],
 '10': ['Preps'],
 '11': ['Number'],
 '12': ['Affect']}

相关问题 更多 >

    热门问题