简体   繁体   中英

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.

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

The function self.cluster.execCmdVerify obviously returns an iterable , so you can simply do this:

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 .

怎么样输出

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 :

cat yourfile | grep -v '#'

EDIT:

if you don't need cat, you can directly do :

grep -v "#" yourfile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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