gpt4 book ai didi

python - 如何在文件中查找标记,然后计算该标记之前的空格数?

转载 作者:行者123 更新时间:2023-11-30 22:29:27 26 4
gpt4 key购买 nike

使用 python,我尝试在文件中搜索标记,然后计算该标记之前到行开头的空格数。

如果文件是这样的:

<index>

<scm>
</scm>

</index>

我想查找 <scm> 之前的空格数

最佳答案

单行模式的解决方案:

import itertools

with open('yourfile.txt', 'r') as f:
txt = f.read()
print(len(list(itertools.takewhile(lambda c: c.isspace(), txt[txt.index('<scm>')-1::-1]))))

输出:

5
<小时/>
  • txt[txt.index('<scm>')-1::-1] - 从字符串 <scm> 的位置“反转”切片到文本开头

  • itertools.takewhile(func, iterable) - 将从输入字符串(可迭代)中累积值/字符,直到值/字符为空格( c.isspace() )

关于python - 如何在文件中查找标记,然后计算该标记之前的空格数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46362358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com