gpt4 book ai didi

Python 在括号内的空格或句子上拆分字符串

转载 作者:行者123 更新时间:2023-11-28 22:15:08 25 4
gpt4 key购买 nike

我想知道是否可以拆分一个字符串,例如

string = 'hello world [Im nick][introduction]'

放入一个数组,例如

['hello', 'world', '[Im nick][introduction]']

它不一定是高效的,只是一种从句子拆分中获取所有单词的方法,除非它们在括号中,整个句子没有拆分。

我需要这个,因为我有一个 markdown 文件,里面有

- What is the weather in [San antonio, texas][location]

我需要 san antonio texas 成为数组中的完整句子,这可能吗?该数组看起来像:

array = ['what', 'is', 'the', 'weather', 'in', 'San antonio, texas][location]']

最佳答案

也许这对你有用:

>>> s = 'What is the weather in [San antonio, texas][location]'
>>> i1 = s.index('[')
>>> i2 = s.index('[', i1 + 1)
>>> part_1 = s[:i1].split() # everything before the first bracket
>>> part_2 = [s[i1:i2], ] # first bracket pair
>>> part_3 = [s[i2:], ] # second bracket pair
>>> parts = part_1 + part_2 + part_3
>>> s
'What is the weather in [San antonio, texas][location]'
>>> parts
['What', 'is', 'the', 'weather', 'in', '[San antonio, texas]', '[location]']

它搜索左括号并在按空格拆分之前将其用作引用。

假设:

  • 第一个右括号和第二个左括号之间没有其他文本。
  • 第二个右括号后没有任何内容

这是一个更强大的解决方案:

def do_split(s):
parts = []

while '[' in s:
start = s.index('[')
end = s.index(']', s.index(']')+1) + 1 # looks for second closing bracket
parts.extend(s[:start].split()) # everything before the opening bracket
parts.append(s[start:end]) # 2 pairs of brackets
s = s[end:] # remove processed part of the string

parts.extend(s.split()) # add remainder

return parts

这会产生:

>>> do_split('What is the weather in [San antonio, texas][location] on [friday][date]?')
['What', 'is', 'the', 'weather', 'in', '[San antonio, texas][location]', 'on', '[friday][date]', '?']

关于Python 在括号内的空格或句子上拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52992147/

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