我想在python-examp中列出字符串

2024-09-29 17:16:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想列出字符串后面的字符串。你知道吗

STUDENT
a john
a anny
SUBJECT
b math
b physical
CLASS
a one
a two
a three
STUDENT
a pone
b julia
b sopia
CLASS
a four
a five
PROFESSOR
b uno
b sonovon
PROFESSOR
b jone

我的目标是删除重复的主题和加入内容。你知道吗

主题可以是随机的上弦。你知道吗

但是内容必须是start ab

我该怎么做?你知道吗


Tags: 字符串内容主题mathjohnonestudentclass
2条回答

因为关于主题的唯一信息是它们是上字符串,所以可以使用isupper()谓词按以下方式拆分文件:

def split_string(file_name):
    list_ = [ x for x in open(file_).read().splitlines()]
    for i,j in enumerate(list_):
        if not (j.isupper() and list_[i + 1].isupper()):
            print j 
split(file_name)

注意:我假设您的字符串存储在一个文件中

只需以主语为键对dict中的元素进行分组:

from collections import OrderedDict
od = OrderedDict()
with open("match.txt") as f:
    key = next(f)
    for line in f:
        if line.startswith(("a","b")):
            od.setdefault(key,[]).append(line)
        else:
            key = line

输出:

for sub,cont in od.items():
    print("{}, {}".format(sub, cont))

STUDENT
, ['a john\n', 'a anny\n', 'a pone\n', 'b julia\n', 'b sopia\n']
SUBJECT
, ['b math\n', 'b physical\n']
CLASS
, ['a one\n', 'a two\n', 'a three\n', 'a four\n', 'a five\n']
PROFESSOR
, ['b uno\n', 'b sonovon\n', 'b jone']

我的目标是删除重复主题并加入内容。很明显这就是你想要的。你知道吗

OrderedDict将保持有序,如果您想将更新的行写入文件,只需重新打开并在迭代时写入即可。items?你知道吗

with open("match.txt", "w") as f:
    for sub, cont in od.items():
        f.write(sub)
        f.writelines(cont)

新输出,由主题连接:

STUDENT
a john
a anny
a pone
b julia
b sopia
SUBJECT
b math
b physical
CLASS
a one
a two
a three
a four
a five
PROFESSOR
b uno
b sonovon
b jone

相关问题 更多 >

    热门问题