2013-06-05 56 views
0

,所以我有这样的文字(共发现)文件由数字和文字,例如像这样的 -使用字符串中的一个整数创建一个字典(或列表)与许多数字

"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'] 

显然,这并不运行,但如果任何人都可以给我任何指针也将不胜感激

回答

5
>>> 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']} 
+0

优秀!还有一件事,如果整个文本行是这样的话,有没有办法阻止它最后一句话: 09827177 18 n 03贵族0 blue_blood 0贵族0 013 @ 09646208 n 0000 – Johnnerz

+0

@Johnnerz,当然我把它添加到我的回答 –

+0

嘿,还有一件小事情,在这些行中,我想添加任何东西后|并将其作为该密钥的另一个条目,我该怎么做? '09826918 18 n 01 Argive 0 002 @ 09729560 n 0000 + 08804512 n 0101 |阿尔戈斯市的本地居民或居民 – Johnnerz

0
res = {} 
with open('nouns.txt','r') as f: 
    for line in f: 
     splited = line.split() 
     res[splited[0]] = [w for w in splited[4:] if not w.isdigit()] 

输出:

{'09807754': ['aristocrat', 'blue_blood', 'patrician']} 
相关问题