【问题标题】:python split string by delimiter only it is outside of quotespython通过分隔符分割字符串,只有它在引号之外
【发布时间】:2019-05-30 17:00:30
【问题描述】:

我的字符串格式如下:

string = 'token1 -token2 +"token 3"'

我想提取tokens和fields如下:

result = [
    'token1',
    '-token2',
    '+token 3'
]

我为此使用了csv 模块,但未能成功获得最后一个令牌为'+"token', '3"'

# for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

tokens = csv.reader(f, delimiter=' ', doublequote=False, quotechar='"', quoting=csv.QUOTE_NONE)

for t in tokens: print(t)
# > ['token1', '-token2', '+"token', '3"']

【问题讨论】:

  • 没有可以使用的准确、正确的格式。您是否可以在源 csv 文件中提供更多详细信息或任何其他模式?
  • +- 是可选的,如果其中有一个或多个空格,则标记将被引用。这是完整的模式。

标签: python csv parsing


【解决方案1】:

我为这个特定案例编写了一个客户拆分器,因为格式太具体了。以下代码适用于提供的输入。

# for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

def check_and_split(line):
    tokens = []
    is_quote = False
    token = ''
    for c in line:
        if c == ' ' and (not is_quote):
            is_quote = False
            tokens.append(token)
            token = ''
        elif c == '"':
            is_quote = True
        else:
            token += c
    tokens.append(token)
    return tokens


for line in f:
    tokens = check_and_split(line)
    for t in tokens: 
        print(t)

输出:

token1
-token2
+token 3

【讨论】:

  • 感谢您的解决方案。虽然elif c == '"': 中的语句需要从is_quote = True 更改为is_quote = not is_quote 以处理第一个标记有引号的情况
【解决方案2】:

csv 不会将 +"token 3" 识别为单个值,因为引号不会包围整个内容。所以确保他们这样做:

line = line.replace('+"', '"+')

并将csv.QUOTE_NONE 更改为csv.QUOTE_MINIMAL(或直接删除quoting arg)。

【讨论】:

    猜你喜欢
    • 2012-07-31
    • 1970-01-01
    • 2021-06-12
    • 2011-03-26
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多