简体   繁体   English

Python通过单引号解析字符串

[英]Python Parseing String by Single Quotes

I am trying to Parse the following string: 我正在尝试解析以下字符串:

EDITED to account for spaces... 编辑占空间...

['THE LOCATION', 'THE NAME', 'THE JOB', 'THE AREA')]

Right now I use regular expressions and split the data with the comma into a list 现在我使用正则表达式,并用逗号将数据分成一个列表

InfoL = re.split(",", Info) InfoL = re.split(“,”,Info)

However my output is 但是我的输出是

'THE LOCATION'
'THE NAME'
'THE JOB'
'THE AREA')]

Looking to have the output as follows 希望得到如下输出

THE LOCATION
THE NAME
THE JOB
THE AREA

Thoughts? 有什么想法吗?

One possibility is to use strip() to remove the unwanted characters: 一种可能性是使用strip()删除不需要的字符:

In [18]: s="['LOCATION', 'NAME', 'JOB', 'AREA')]"

In [19]: print '\n'.join(tok.strip("[]()' ") for tok in s.split(','))
LOCATION
NAME
JOB
AREA

Like your original solution, this will break if any of strings are allowed to contain commas. 像您的原始解决方案一样,如果允许任何字符串包含逗号,则此方法将中断。

PS If that closing parenthesis in your example is a typo, you might be able to use ast.literal_eval() : PS:如果您的示例中的ast.literal_eval()括号是一个错字,则可以使用ast.literal_eval()

In [22]: print '\n'.join(ast.literal_eval(s))
LOCATION
NAME
JOB
AREA
InfoL = re.split("[, '()\[\]]*", Info)

try this code snippet : 试试这个代码片段:

import re
tmpS = "['THE LOCATION', 'THE NAME', 'THE JOB', 'THE AREA')]"
tmpS = re.sub('[^\w\s,]+', '', tmpS)
print tmpS # Result -> 'THE LOCATION, THE NAME, THE JOB, THE AREA'
for s in tmpS.split(','):
     print s.strip()


O/P:
THE LOCATION
THE NAME
THE JOB
THE AREA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM