猿问

使用字符串中的整数创建具有这么多数字的字典(或列表)

所以我有这个由数字和单词组成的文本(wordnet)文件,例如这样的-


"09807754 18 n 03 aristocrat 0 blue_blood 0 patrician"

我想读第一个数字作为其后单词的字典名称(或列表)。它的布局永远不会改变,它始终是一个8位数字的键,后跟两位数字,一个字母和两位数字。最后两位数字(03)表示与前8位数字键关联的单词数(在这种情况下为三个单词)。


我的想法是我将在字符串中搜索第14位,并使用该数字运行循环以选择与该键相关的所有单词


所以我认为它会像这样


with open('nouns.txt','r') as f:

    for line in f:


        words = range(14,15)

        numOfWords = int(words)

            while i =< numOfWords

                #here is where the problem arises, 

                #i want to search for words after the spaces 3 (numOfWords) times 

                #and put them into a dictionary(or list) associated with the key

                range(0,7) = {word(i+1), word(i+2)}

从技术上讲,我正在寻找以下任何一种更有意义:


09807754 = { 'word1':aristocrat, 'word2':blue_blood , 'word3':patrician }

or

09807754 = ['aristocrat', 'blue_blood', 'patrician']

显然,这不会运行,但是如果有人可以给我任何指示,将不胜感激


泛舟湖上清波郎朗
浏览 435回答 2
2回答

慕斯709654

>>> L = "09807754 18 n 03 aristocrat 0 blue_blood 0 patrician".split()>>> L[0], L[4::2]('09807754', ['aristocrat', 'blue_blood', 'patrician'])>>> D = {}>>> D.update({L[0]: L[4::2]})>>> D{'09807754': ['aristocrat', 'blue_blood', 'patrician']}对于您的注释中的额外行,需要一些额外的逻辑>>> L = "09827177 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 @ 09646208 n 0000".split()>>> D.update({L[0]: L[4:4 + 2 * int(L[3]):2]})>>> D{'09807754': ['aristocrat', 'blue_blood', 'patrician'], '09827177': ['aristocrat', 'blue_blood', 'patrician']}

阿晨1998

res = {}with open('nouns.txt','r') as f:&nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; splited = line.split()&nbsp; &nbsp; &nbsp; &nbsp; res[splited[0]] = [w for w in splited[4:] if not w.isdigit()]&nbsp;输出:{'09807754': ['aristocrat', 'blue_blood', 'patrician']}
随时随地看视频慕课网APP

相关分类

Python
我要回答