Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python仅按分隔符拆分字符串它位于引号之外_Python_Csv_Parsing - Fatal编程技术网

python仅按分隔符拆分字符串它位于引号之外

python仅按分隔符拆分字符串它位于引号之外,python,csv,parsing,Python,Csv,Parsing,我的字符串具有以下格式: string = 'token1 -token2 +"token 3"' 我想提取令牌和字段,如下所示: result = [ 'token1', '-token2', '+token 3' ] 我正在使用csv模块进行此操作,但未能成功获取最后一个令牌,即'+“令牌”,“3” 我为这个特定的案例编写了一个客户拆分器,因为格式太具体了。以下代码适用于提供的输入 # for Python 2.x try: from StringIO impor

我的字符串具有以下格式:

string = 'token1 -token2 +"token 3"'
我想提取令牌和字段,如下所示:

result = [
    'token1',
    '-token2',
    '+token 3'
]
我正在使用
csv
模块进行此操作,但未能成功获取最后一个令牌,即
'+“令牌”,“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"')

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

csv没有将
+“token 3”
识别为单个值,因为引号没有围绕整个值。因此,确保他们做到:

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

然后将
csv.QUOTE\u NONE
更改为
csv.QUOTE\u MINIMAL
(或者干脆删除
quoting
arg)。

没有准确、正确的格式可供使用。是否在源csv文件中提供更多详细信息或任何其他模式?
+
-
是可选的,如果令牌中有一个或多个空格,则会引用它们。这是完整的模式。感谢您的解决方案。尽管
elif c==''“:
中的语句需要从
is\u quote=True
更改为
is\u quote=not is\u quote
,以便处理第一个标记有引号的情况
line = line.replace('+"', '"+')