gpt4 book ai didi

python - 在Python中多次分割字符串

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

这应该是一件简单的事情,但我无法让它发挥作用。

假设我有这个字符串。

I want this string to be splitted into smaller strings.

而且,我想将其分割成更小的字符串,但只取 T 和 S 之间的内容。

所以,结果应该是这样的

this, to be s, to s, trings

到目前为止,我已经尝试过在每个 S 上进行拆分,然后直到每个 T (向后)。然而,它只会得到第一个“this”,然后停止。我怎样才能让它继续下去并得到T和S之间的所有东西?

(在此程序中,我将结果导出到另一个文本文件)

matches = open('string.txt', 'r')

with open ('test.txt', 'a') as file:
for line in matches:
test = line.split("S")
file.write(test[0].split("T")[-1] + "\n")

matches.close()

也许使用正则表达式会更好,尽管我不知道如何很好地使用它们?

最佳答案

您需要使用 re.findall() 调用:

re.findall(r't[^s]*s', line, flags=re.I)

演示:

>>> import re
>>> sample = 'I want this string to be splitted into smaller strings.'
>>> re.findall(r't[^s]*s', sample, flags=re.I)
['t this', 'tring to be s', 'tted into s', 'trings']

请注意,这与 't this''tted into s' 相匹配;您的规则需要澄清为什么那些前 t 字符在 'trings' 匹配时不应该匹配。

听起来好像您只想匹配 ts 之间的文本,而不包含任何其他 t :

>>> re.findall(r't[^ts]*s', sample, flags=re.I)
['this', 'to be s', 'to s', 'trings']

其中第二个结果中的 tring 和第三个结果中的 tted 不包括在内,因为这些结果中有一个较晚的 t

关于python - 在Python中多次分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20951933/

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