简体   繁体   English

阅读txt并制作“列表列表”

[英]Reading a txt and making a “list of lists”

I want to make a program that reads a .txt file that looks like this: 我想制作一个读取.txt文件的程序,如下所示:

[LIST 1] [清单1]

var1,var2,var3,var4 var1,var2,var3,var4

var5,var6 var5,var6

[LIST 2] [清单2]

var7,var8,var9 var7,var8,var9

And as the title says, I want to make a list of all the terms between "[","]" and create a list for each of these terms composed of the terms listed under them (for example: LIST2 = [var7, var8, var9] ). 就像标题所说的那样,我想列出“ [”,“]”之间的所有术语,并为这些术语下的每个术语创建一个列表(例如: LIST2 = [var7, var8, var9] )。

So far, I made a list of the terms between "[]": 到目前为止,我列出了“ []”之间的术语:

try:
f = open("tm.txt", "r")
try:
    string = f.read()       
finally:
    f.close()
except IOError:
    pass

lista = re.findall(re.escape("[")+"(.*)"+re.escape("]"),string)

for i in range(len(lista)):
    vars()[lista[i]] = i   #makes str into var and gives a value to them
    print vars()[lista[i]] #prints what is inside of each var of the list
print lista #prints each var names

As you can see, the only thing left to do is to assign each of these newly made variables to the list of terms that are under them on the .txt file. 如您所见,剩下要做的就是将每个新创建的变量分配给.txt文件中它们之下的术语列表。 I'm trying to do that so I can make a configurator via TKinter for an Indie game I'm making. 我正在尝试这样做,因此我可以通过TKinter为正在制作的独立游戏制作配置器。 Editing the .txt files themselves is pretty annoying. 编辑.txt文件本身很烦人。

From the examples section of the ConfigParser module: ConfigParser模块的示例部分中:

>>> import ConfigParser
>>> import io
>>> s = """[LIST 1]
... 
... var1,var2,var3,var4
... 
... var5,var6
... 
... [LIST 2]
... 
... var7,var8,var9"""
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(io.BytesIO(s))
>>> config.items('LIST 1')
[('var1,var2,var3,var4', None), ('var5,var6', None)]

I thought you might don't have any intention to using Modules(like Myslef),So I Suggest This: 我以为您可能不打算使用模块(例如Myslef),所以我建议这样做:

file1 = open('tm.txt')
flist = file1.readlines()
file1.close()
flist = [i.rstrip() for i in flist]
c = 0
final = []
for i in flist:
    if(i == '[LIST {0}]'.format(c+1)):
        temp = []
        final.append(temp)
        c += 1
    else:
        for j in i.split(','):
            temp.append(j)
            final[len(final)-1] = temp
print(final)

# Each Member OF 'final' List is The List You Want!

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

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