私信  •  关注

Mohammad Khoshbin

Mohammad Khoshbin 最近创建的主题
Mohammad Khoshbin 最近回复了
3 年前
回复了 Mohammad Khoshbin 创建的主题 » 使用Python打印特定字符

你可以用 split() 功能:

a = "[xyx],[abc].[cfd],[abc].[dgr],[abc]"

desired_strings = [i.split(',')[0] for i in a.split('.')]

for i,string in enumerate(desired_strings):
    print(f"{i+1}.{string}")
3 年前
回复了 Mohammad Khoshbin 创建的主题 » Python:从文本文件中提取值以创建嵌套字典

如果对txt文件中的每个对象使用字典,则可以循环使用txt文件的行,并使用一些python内置函数,如 readlines() startswith() 做你想做的事。

f = open('sample.txt')
lines = f.readlines()
d = {}
for i,line in enumerate(lines):
    if line[:-2].isnumeric():
        ind =  line[:-2]
        name = lines[i+1].replace('\n', '')
        if not ind in d:
            d[ind] = {}

    if line.startswith('Sub-index'):
        sub_ind = line.split()[-1].split(':')[0]
        if not sub_ind in d[ind]:
            d[ind][sub_ind] = []
            d[ind][sub_ind].append(name)

    if line.startswith('Scale'):
        scale = line.split()[-1]
        d[ind][sub_ind].append(scale)

    if line.startswith('Description'):
        desc = line.split(': ')[-1].replace('\n', '')
        d[ind][sub_ind].append(desc)

输出:

{
    '1': {
        '0': ['Name of Object 1', 'Q0', 'Object 1 does this']
        },
    '2': {
        '0': ['Object 2 yo', 'Q0', 'Something important'],
        '1': ['Object 2 yo', '0.125', 'Object 2 does that']
        }
}