gpt4 book ai didi

python - 查找两个$之间的文本并将它们放入列表中

转载 作者:行者123 更新时间:2023-12-01 04:56:12 25 4
gpt4 key购买 nike

我有一个类似于 - 的文本文件 -

$ abc
defghjik
am here
not now
$ you
are not
here but go there
$ ....

我想提取两个 $ 符号之间的文本并将该文本放入列表或字典中。如何在 python 中通过读取文件来做到这一点?

我尝试了正则表达式,但它给了我文本文件的备用值:

f1 = open('some.txt','r')
lines = f1.read()
x = re.findall(r'$(.*?)$', lines, re.DOTALL)

我希望输出如下所示 -['abc', 'defghjik', '我在这里', '不是现在']['你','不在','这里但去那里']

抱歉,我是 python 新手并正在尝试学习,任何帮助表示赞赏!谢谢!

最佳答案

在正则表达式中 $ 是一个具有特殊含义的字符,需要转义以匹配文字字符。另外,为了匹配多个部分,我会使用 lookahead (?=...) 断言,断言与文字 $ 字符匹配。

>>> x = re.findall(r'(?s)\$\s*(.*?)(?=\$)', lines)
>>> [i.splitlines() for i in x]
[['abc', 'defghjik', 'am here', 'not now'], ['you', 'are not', 'here but go there']]

Working Demo

关于python - 查找两个$之间的文本并将它们放入列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27327763/

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