Python 在引号上拆分字符串 [英] Python split string on quotes

查看:41
本文介绍了Python 在引号上拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名 Python 学习者.如果我的文件中有一行文本,看起来像这样

I'm a python learner. If I have a lines of text in a file that looks like this

"Y:\DATA\00001\SERVER\DATA.TXT" "V:\DATA2\00002\SERVER2\DATA2.TXT"

"Y:\DATA\00001\SERVER\DATA.TXT" "V:\DATA2\00002\SERVER2\DATA2.TXT"

我可以将引号周围的行分开吗?唯一的常量是它们在文件中相对于数据行本身的位置.数据行的范围可以从 10 到 100+ 个字符(它们将是嵌套的网络文件夹).我看不出如何使用任何其他方式来分割这些标记,但我缺乏 Python 知识使这变得困难.我试过了

Can I split the lines around the inverted commas? The only constant would be their position in the file relative to the data lines themselves. The data lines could range from 10 to 100+ characters (they'll be nested network folders). I cannot see how I can use any other way to do those markers to split on, but my lack of python knowledge is making this difficult. I've tried

optfile=line.split("")

和其他变体,但不断收到 valueerror: empty separator.我明白为什么这么说,我只是不知道如何改变它.一如既往地非常感谢任何帮助.

and other variations but keep getting valueerror: empty seperator. I can see why it's saying that, I just don't know how to change it. Any help is, as always very appreciated.

非常感谢

推荐答案

查找所有正则表达式匹配即可:

Finding all regular expression matches will do it:

input=r'"Y:\DATA\00001\SERVER\DATA.TXT" "V:\DATA2\00002\SERVER2\DATA2.TXT"'

re.findall('".+?"', # or '"[^"]+"', input)

这将返回文件名列表:

["Y:\DATA\00001\SERVER\DATA.TXT", "V:\DATA2\00002\SERVER2\DATA2.TXT"]

要获取不带引号的文件名,请使用:

To get the file name without quotes use:

[f[1:-1] for f in re.findall('".+?"', input)]

或使用 re.finditer:

[f.group(1) for f in re.finditer('"(.+?)"', input)]

这篇关于Python 在引号上拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆