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
最好的方法是使用
^{pr2}$re
总的来说,这将变成:
第一个生成器将打开的文件句柄分成不同的行。然后它试图分割线。如果成功,则生成一个包含不同部分的元组,否则将生成原始字符串。在
在实际的程序中,可以将
StringIO(test_str)
替换为open(filename, 'r')
你原来的字符串一开始引用得不好。 您可以在引号前面加上一个\号来转义引号:
然后,可以按如下方式进行拆分:
^{pr2}$在我看来,您只希望在第一次出现}保留在输出列表的第二个元素中。在
"
时拆分,并希望将所有{下面是一个仅使用标准库的示例,不需要导入:
输出:
^{pr2}$或者,如果打印输出列表的各个元素:
输出:
[根据评论编辑]
根据注释,您可以使用
.split('"', 1)
,例如:[根据更新的问题和评论进行编辑]
OP评论:
随着问题在输入上用尾随的“is something”字符串更新,输出中需要省略该字符串,示例现在变成如下:
然而,一个文件可能包含多行,如果这种情况下,您需要建立一个输出列表,每行一个输出。现在的示例如下:
相关问题 更多 >
编程相关推荐