简体   繁体   English

在python中解析字符串列表

[英]Parsing string list in python

I am trying to remove the comments when printing this list. 我正在尝试在打印此列表时删除评论。

I am using 我在用

output = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')
for item in output:
    print item

This is perfect for giving me the entire file, but how would I remove the comments when printing? 这非常适合给我整个文件,但是在打印时如何删除注释?

I have to use cat for getting the file due to where it is located. 由于文件所在位置,我必须使用cat来获取文件。

您可以使用regex re模块来标识注释,然后将其删除或在脚本中忽略它们。

The function self.cluster.execCmdVerify obviously returns an iterable , so you can simply do this: 函数self.cluster.execCmdVerify显然返回了iterable ,因此您可以简单地执行以下操作:

import re

def remove_comments(line):
    """Return empty string if line begins with #."""
    return re.sub(re.compile("#.*?\n" ) ,"" ,line)
    return line

data = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')

for line in data:
    print remove_comments(line)

The following example is for a string output: 以下示例用于字符串输出:

To be flexible, you can create a file-like object from the a string (as far as it is a string) 为了灵活起见,您可以从字符串(就字符串而言)创建类似文件的对象

from cStringIO import StringIO
import re

def remove_comments(line):
    """Return empty string if line begins with #."""
    return re.sub(re.compile("#.*?\n" ) ,"" ,line)
    return line

data = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')
data_file = StringIO(data)

while True:
    line = data_file.read()
    print remove_comments(line)
    if len(line) == 0:
        break

Or just use remove_comments() in your for-loop . 或者只是在for-loop使用remove_comments()

怎么样输出

grep -v '#' /opt/tpd/node_test/unit_test_list

If it's for a python file for example and you want to remove lines beginning with # you can try : 例如,如果用于python文件,并且您想删除以#开头的行,则可以尝试:

cat yourfile | grep -v '#'

EDIT: 编辑:

if you don't need cat, you can directly do : 如果您不需要猫,可以直接做:

grep -v "#" yourfile

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

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