在python中用双引号拆分

2024-10-01 19:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

import shlex
fil=open("./demoshlex.txt",'r')
line=fil.readline()
print line
print shlex.split(line)

假设我的刺在一个文本文件中如下所示

第1行:

^{pr2}$

我想拆分行并形成如下列表

[asfdsafadfa, "Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf '0000000000000000000000000000000'.", is something]

我尝试使用shlex.split,但它给了我异常,将代码和异常放在一起

**Output:**
python basicshelx.py
asfdsafadfa "Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf '0000000000000000000000000000000'."

Traceback (most recent call last):
File "basicshelx.py", line 5, in <module>
print shlex.split(line)
File "/home/siddhant/sid/.local/lib/python2.7/shlex.py", line 279, in split
return list(lex)
File "/home/siddhant/sid/.local/lib/python2.7/shlex.py", line 269, in next
token = self.get_token()
File "/home/siddhant/sid/.local/lib/python2.7/shlex.py", line 96, in get_token
raw = self.read_token()
File "/home/siddhant/sid/.local/lib/python2.7/shlex.py", line 172, in read_token
raise ValueError, "No closing quotation"
ValueError: No closing quotation

Tags: inpytokenhomeliblocallinefile
3条回答

最好的方法是使用re

s = '''asfdsafadfa "Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf '0000000000000000000000000000000'." is something'''''

pat = re.compile(
    r'''
    ^      # beginning of a line
    (.*?)  # first part. the *? means non-greedy
    (".*") # part between the outermost ", ("-included)
    (.*?)  # last part
    $      # end of a line
    ''', re.DOTALL|re.VERBOSE)
pat.match(s).groups()
^{pr2}$

总的来说,这将变成:

test_str = '''asfdsafadfa "Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf '0000000000000000000000000000000'." is something
asfdsafadfa "Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf '0000000000000000000000000000000'."
asfdsafadfa Tabvxc avcxsdasaf sadasfdf. sdsadsaf '0000000000000000000000000000000'.
'''
def split_lines(filehandle):
    pat = re.compile(r'''^(.*?)(".*")(.*?)$''', re.DOTALL)
    for line in filehandle:
        match = pat.match(line)
        if match:
            yield match.groups()
        else:
            yield line

with StringIO(test_str) as openfile:
    for line in split_lines(openfile):
        print(line)

第一个生成器将打开的文件句柄分成不同的行。然后它试图分割线。如果成功,则生成一个包含不同部分的元组,否则将生成原始字符串。在

在实际的程序中,可以将StringIO(test_str)替换为open(filename, 'r')

('asfdsafadfa ', '"Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf \'0000000000000000000000000000000\'."', ' is something')
('asfdsafadfa ', '"Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf \'0000000000000000000000000000000\'."', '')
asfdsafadfa Tabvxc avcxsdasaf sadasfdf. sdsadsaf '0000000000000000000000000000000'.

你原来的字符串一开始引用得不好。 您可以在引号前面加上一个\号来转义引号:

my_var = "Tabvxc \"avcx\"sdasaf\" sadasfdf. sdsadsaf '0000000000000000000000000000000'."

然后,可以按如下方式进行拆分:

^{pr2}$

在我看来,您只希望在第一次出现"时拆分,并希望将所有{}保留在输出列表的第二个元素中。在

下面是一个仅使用标准库的示例,不需要导入:

result = []
with open('test.txt', 'r') as openfile:
    for line in openfile:
        # strip spaces and \n from the line
        line = line.strip()
        # split the line on "
        my_list = line.split('"')
        # only append first element of the list to the result
        result.append(my_list[0].strip())
        # rebuild the second part, adding back in the "
        remainder = '"' + '"'.join([a for a in my_list[1:]])
        # append the second part to the result
        result.append(remainder)
print(result)

输出:

^{pr2}$

或者,如果打印输出列表的各个元素:

for e in result:
    print(e)

输出:

asfdsafadfa
"Tabvxc "avcx"sdasaf" sadasfdf. sdsadsaf '0000000000000000000000000000000'."

[根据评论编辑]

根据注释,您可以使用.split('"', 1),例如:

with open('test.txt', 'r') as openfile:
    for line in openfile:
        # strip spaces and \n from the line
        line = line.strip()
        # split the line on " but only the fist one
        result = line.split('"', 1)
        # add in the " for the second element
        result[1] = '"' + result[1]

[根据更新的问题和评论进行编辑]

OP评论:

I want only the quoted part i.e remove "is something" from that element of result List and make it [2] element

随着问题在输入上用尾随的“is something”字符串更新,输出中需要省略该字符串,示例现在变成如下:

with open('test.txt', 'r') as openfile:
    for line in openfile:
        # strip spaces and \n from the line
        line = line.strip()
        # split the line on " but only the fist one
        result = line.split('"', 1)
        # add in the " for the second element, remove trailing string
        result[1] = '"{}"'.format(result[1].rsplit('"', 1)[0])

然而,一个文件可能包含多行,如果这种情况下,您需要建立一个输出列表,每行一个输出。现在的示例如下:

result = []
with open('test.txt', 'r') as openfile:
    for line in openfile:
        if '"' in line:
            # we can split the line on "
            line = line.strip().split('"', 1)
            if line[1][-1] == '"':
                # no trailing string to remove
                # pre-fix second element with "
                line[1] = '"{}'.format(line[1])
            elif '"' in line[1]:
                # trailing string to be removed with .rsplit()[0]
                # post- and pre-fix " for second element 
                line[1] = '"{}"'.format(line[1].rsplit('"', 1)[0])
        else:
            # no " in line, return line as one element list
            line = [line.strip()]
        result.append(line)

# result is now a list of lists
for line in result:
    for e in line:
        print(e)

相关问题 更多 >

    热门问题