【问题标题】:Finding the length of a certain part of a list查找列表特定部分的长度
【发布时间】:2022-07-23 06:08:54
【问题描述】:

我试图弄清楚如何找到列表中某个部分的长度。例如,我的程序在我的配置文件中有一个用户名和密码。有没有办法弄清楚有多少个用户名?如果是,那怎么办?

#Also any of the spaces you see between the words are just for reading's sake
#and won't be there in the final program

firsttime:
True

Username:
user1
user2

Password:
pass1
pass2

Key:
key

Theme:
#303030
white

【问题讨论】:

  • 如果您可以控制配置文件的格式,那么您应该考虑使用像 json 或 yaml 这样的数据格式,这使得这种类型的结构化数据交互更加容易。
  • 就像@Conor 说的:使用json 配置文件并使用json 标准模块读取它
  • 感谢您的建议。我真的不知道如何使用,但我看看。

标签: python list


【解决方案1】:

如果我们假设您的配置行存储在一个名为 my_conf.cfg 的文件中,我们可以尝试编写这样的自定义解析器:

with open('(...)/my_conf.cfg') as cf:
    _con_lines = cf.readlines()

configuration = {}
for c_l in _con_lines:
    c_l.strip('\n')
    if not c_l or c_l.startswith('#'):
    
        continue
    if c_l.endswith(':'):
        key = c_l[:-1]
        configuration[key] = []
    else:
        configuration[key].append(c_l)

那么你的问题的答案是

len(configuration['Username'])

【讨论】:

  • configuration[key].append(c_l) UnboundLocalError: local variable 'key' referenced before assignment 有没有办法解决这个问题?
  • 如果您使用的文件与问题中的文件不同,则可能会发生这种情况,其中第一行不是 cmets(以“#”开头),也不是空行,也不是键(以冒号结尾) .也许一行只有一些空格,在这种情况下,我会将if not c_l (...) 替换为if not c_l.strip() (...)。如果还是不行,而且配置文件和问题完全一样,就应该探索其他解决方案,比如不同的行字符,比如\r\r\n,而不是\n
【解决方案2】:

回复我自己的帖子很晚,但我制作了自己的某种解析器,在我看来效果很好。

# dictionary.txt can be replaced with any file

def gettext(header, move, count):
    with open('dictionary.txt', 'r') as f:
        f = f.read()
        lines = f.split("\n")

    for i, line in enumerate(lines):
        if header in line:
            word = []
            for l in range(0, count):
                newindex = i + move
                word.append(lines[newindex+l])

            return "\n".join(word)

这适用于我所拥有的任何文件格式。 header 变量是您要查找的标头,然后查找字符串。您甚至可以使用 count 变量将多行连接在一起,move 用于向下查看 x 行然后抓取字符串。

【讨论】:

    猜你喜欢
    • 2015-01-02
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多