开发者

parsing text file for a line, in python

system generates a text file. it contains more than 100 lines. i like to get a line in the file.

some text **
Actions Pending are: Action-1, Action-2,....Action-3 (this is another new line)
some text**

need to get the Actions in pending to array.

i used

for index in text:
    rc.logMessage(str(index))

it is pr开发者_运维技巧inting each character at a time not the line.

help me how can i parse this file to get actions into an array.

Thanks in advance


Something like:

d = """some text **
Actions Pending are: Action-1, Action-2, Action-3
some text**
"""
res = []
for line in re.findall('Actions Pending are: (.+)', d):
    res.extend([action.strip() for action in line.split(',')])
['Action-1', 'Action-2', 'Action-3']


You can try something like this:

pendingActions = []
textToSearch = 'Actions Pending are:'
for line in open(filename, 'r'):
    line = line.strip()
    if line and line.startswith(textToSearch):
        pendingActions.extend([x.strip() for x in line[len(textToSearch):].split(',') if x.strip()])


You need to iterate over the file, not a string read from the file.

with open(filename) as text:
    for line in text:
         rc.logMessage(some_function_of_the_line(line))

Iterating over the file gives you lines; iterating over a string gives you characters / bytes.


You want str.splitlines() http://docs.python.org/library/stdtypes.html#str.splitlines

for index in text:
    rc.logMessage(str(index))

becomes:

for index in text.splitlines():
    rc.logMessage(str(index))


Try something like this

with file("your_file") as logfile:
   result = [line for line in logfile if line.startswith("Actions pending")]

This way in result you will have all the actions lines.


    search_string = 'Actions Pending are: '
    for line in open('yourfile.txt', 'r').readlines():
      if line.startswith(search_string):
        actions = line[len(search_string):].split(',')
        break
    print actions

Artsiom was faster: parsing text file for a line, in python, maybe my version is more readable.


Here is a one-liner (for fun):

s = """some text **
Actions Pending are: Action-1, Action-2, Action-3
Actions Pending are: Action-4, Action-5, Action-6
some text**"""

[a for ln in s.splitlines() if ln.startswith("Actions Pending") for a in ln[len("Actions Pending are: "):].split(', ')]
------
['Action-1', 'Action-2', 'Action-3', 'Action-4', 'Action-5', 'Action-6']

To use a file instead of a string, replace s.splitlines() with f.readlines(). Note, I wouldn't use this code in practice; It is just for fun.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜