简体   繁体   English

将文本文件转换为以行号为值的字典

[英]Convert text file into dictionary with line number as value

I have to convert text file into dictionary and use line number as a value for dictionary.我必须将文本文件转换为字典并使用行号作为字典的值。

Example text file 'test.txt':示例文本文件“test.txt”:

aaaa 4.5啊啊4.5

bbbb bbbb

3 cccc dddd 3 cccc dddd

Output I need to get is dictionary looking like this: Output我需要得到的是这样的字典:

{'aaa':1, 4.5:1, 'bbbb':2, 3:3, 'cccc':3, 'dddd':3} {'aaa':1, 4.5:1, 'bbbb':2, 3:3, 'cccc':3, 'dddd':3}

I think this should work as in the above answer the last string will contain \n我认为这应该像上面的答案一样工作,最后一个字符串将包含\n

val = 1
dic = {}
with open("a.txt") as a:
    for line in a:
        a = line.split(" ")
        for ech in a:
            dic[ech.replace("\n","")] = val
        val += 1

print(dic)

This is a simple way to do it:这是一个简单的方法:

filename = "C:/Users/henri/Downloads/test.txt"    # your own filename
f = open(filename, 'r')                           # open file reader
lis = f.readlines()                               # read all lines into a list
dic = {}                                          # make empty dictionary

for i,line in enumerate(lis):                     # loop through lines
    line = line.rstrip("\n")                      # remove trailing newline
    parts = line.split()                          # split into all parts of line

    for a in parts:                               # loop thourhg all the parts of the line
        dic[line] = i+1                           # add to dictionary

print(dic)

edit: didnt see that you wanted to split the lines at whitespaces, added it...编辑:没有看到你想在空格处分割行,添加它......

dct = {} with open('file.txt') as f: for index, line in enumerate(f): for token in line.split(): dct[token] = index+1 print(dct)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM