【问题标题】:splting a string in python using space as delimiter unless the space is found between quotation marks [duplicate]除非在引号之间找到空格,否则使用空格作为分隔符在python中拆分字符串[重复]
【发布时间】:2021-04-20 11:36:43
【问题描述】:

我想使用空格作为分隔符来分割文本,除非在引号之间找到空格

例如

string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]

【问题讨论】:

  • @ChrisLear 被标记为 Java,我认为它不适用于 python 的正则表达式。
  • 无需使用正则表达式,import shlex; shlex.split(text, posix=False)。见the answer
  • @WiktorStribiżew,尽管我得到了答案,但我同意该链接。我不知道那个模块!效果很好。

标签: python regex


【解决方案1】:

遍历字符串:

string = "my name is 'solid snake'"
quotes_opened = False
out = []
toadd = ''
for c, char in enumerate(string):
    if c == len(string) - 1: #is the character the last char
        toadd += char
        out.append(toadd); break
    elif char in ("'", '"'): #is the character a quote
        if quotes_opened:
            quotes_opened = False #if quotes are open then close
        else:
            quotes_opened = True #if quotes are closed the open
        toadd += char
    elif char != ' ':
        toadd += char #add the character if it is not a space
    elif char == ' ': #if character is a space
        if not quotes_opened: #if quotes are not open then add the string to list
            out.append(toadd)
            toadd = ''
        else: #if quotes are still open then do not add to list
            toadd += char
print(out)

【讨论】:

    【解决方案2】:

    蛮力的方法是:

    string = "my name is 'solid snake'"
    output = ["my","name","is","'solid snake'"]
    
    ui= "__unique__"
    
    string2= string.split("'")
    print(string2)
    
    for i, segment in enumerate(string2):
        if i %2 ==1:
            string2[i]=string2[i].replace(" ",ui)
            
    print(string2)
    
    string3= "'".join(string2)
    
    print(string3)
    
    string4=string3.split(" ")
    
    print(string4)
    
    for i, segment in enumerate(string4):
        if ui in segment:
            string4[i]=string4[i].replace("__unique__", " ")
    
    print()
    print(string4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2014-12-16
      • 2011-01-28
      • 2012-09-03
      相关资源
      最近更新 更多