ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I have text file which is generated on daily base, I'm trying to write script in python to extract some data from that file. file structured is constant, and there are some Variables are changing in each new file mentioned with blue color. The Values with read color are static values.
input file
---------------------------------------------------------------------
THIS IS AUTO GENERATED MESSAGE
---------------------------------------------------------------------
TO: AABBAA KKLLC OMAANNNN TSBBBBI MESSAGE KABBAAA [OOMML]
FROM: MAAA MOONSOR
NOTIFICATION:
AHMED OCESS, BALL ON THE FOLLOWING VALUE EVENT:
SALIMTUDE: 6.6 MWP
ALITH: 10KM
DATE: 31 MAY 2014
KHLGIN TIME: 1154 UTC
OMAITUDE: 18.90SS
UAEGITUDE: 107.40GG
KAIATION: OFF THE OOBBCC
Please any one could advice how can start to write this script.
The same way one starts with any programming problem: break it down into pieces and work out how to do each piece.
You have to do some of the work yourself - it's the only way you'll learn. Tell us how you've broken it down and what you've tried to accomplish each piece.
why python? probably perl would be better. So here are some parts:
possible command line args?
open input file (check name, existence ...)
parse file (check content, collect relevant info)
close input file
create and print output
The same way one starts with any programming problem: break it down into pieces and work out how to do each piece.
You have to do some of the work yourself - it's the only way you'll learn. Tell us how you've broken it down and what you've tried to accomplish each piece.
Thank you for your advice, I was trying different ways before i post the issue in the forum. and I preferred to start with good a logarithm recommended by python experts.
Save the example text file as "test.txt", and then, in the same directory, write and run the following Python file, which I just knocked up:
Code:
#!/usr/bin/env python
def main():
print colored('XXXLL', Colors.Green)
keys = set(['TO:', 'SALIMTUDE:', 'ALITH:', 'DATE:', 'KHLGIN TIME:',
'OMAITUDE:', 'UAEGITUDE:', 'KAIATION:'])
with open('test.txt') as f:
for line in f:
tokens = line.split()
if len(tokens) and tokens[0] in keys:
if tokens[0] == 'TO:':
name = ' '.join(tokens[3:5])
print colored(name, Colors.Blue)
print
else:
left = tokens[0][:3]
red = colored(left, Colors.Red)
right = ' '.join(tokens[1:])
blue = colored(right, Colors.Blue)
print '{0}: {1}'.format(red, blue)
def colored(text, color):
return '{0}{1}{2}'.format(color, text, Colors.End)
class Colors(object):
Red = "\033[91m"
Green = "\033[92m"
Blue = "\033[94m"
Cyan = "\033[96m"
White = "\033[97m"
Yellow = "\033[93m"
Magenta = "\033[95m"
Grey = "\033[90m"
Black = "\033[90m"
Default = "\033[99m"
End = '\033[0m'
if __name__ == '__main__':
main()
It works with Python 2.6 and 2.7.
Quote:
Originally Posted by dugan
Now you've done it.
Save the example text file as "test.txt", and then, in the same directory, write and run the following Python file, which I just knocked up:
Code:
#!/usr/bin/env python
def main():
print colored('XXXLL', Colors.Green)
line_number = 0
keys = set(['TO:', 'SALIMTUDE:', 'ALITH:', 'DATE:', 'KHLGIN TIME:',
'OMAITUDE:', 'UAEGITUDE:', 'KAIATION:'])
with open('test.txt') as f:
for line in f:
tokens = line.split()
if len(tokens) and tokens[0] in keys:
if tokens[0] == 'TO:':
name = ' '.join(tokens[3:5])
print colored(name, Colors.Blue)
print
else:
left = tokens[0][:3]
red = colored(left, Colors.Red)
right = ' '.join(tokens[1:])
blue = colored(right, Colors.Blue)
data = '{0}: {1}'.format(red, blue)
print data
line_number += 1
def colored(text, color):
return '{0}{1}{2}'.format(color, text, Colors.End)
class Colors(object):
Red = "\033[91m"
Green = "\033[92m"
Blue = "\033[94m"
Cyan = "\033[96m"
White = "\033[97m"
Yellow = "\033[93m"
Magenta = "\033[95m"
Grey = "\033[90m"
Black = "\033[90m"
Default = "\033[99m"
End = '\033[0m'
if __name__ == '__main__':
main()
It works with Python 2.6 and 2.7.
1- Thanks dugan for your reply, the code is working well, but there is misunderstanding, I was mean by the color only to mention the information should be in the output so it should be without colors function.
2 - Also I have one extra Question, I want the output to be in new file contains the extracted data can call ( ext_data.txt ).
3 - Some time the input file (test.txt) existing without required data so I want condition if there is no (extracted data) don't create the output file.
4 - also Can I add any Linux command in same python script after finishing the previous steps, such as mv test.txt ../archive/.
Hi a.albreiki. I think I've given you enough code at this point. I can get you started on how you can code the rest (yourself) though:
Quote:
2 - Also I have one extra Question, I want the output to be in new file contains the extracted data can call ( ext_data.txt ).
Code:
with open('ext_data.txt', 'w') as f:
f.write('string')
Quote:
3 - Some time the input file (test.txt) existing without required data so I want condition if there is no (extracted data) don't create the output file.
Oh come on. That's just an if statement.
Code:
4 - also Can I add any Linux command in same python script after finishing the previous steps, such as mv test.txt ../archive/.
Yes you can execute arbitrary external commands. However, you can probably do what you want in straight Python, without the use of external commands. That specifically includes moving files into directories. Look into the following Python modules:
Thank you for your advice, I was trying different ways before i post the issue in the forum. and I preferred to start with good a logarithm recommended by python experts.
Thanks a lot..
I don't see anything logarithmic in your I/O or the code offered. What do you mean? Do you need help with an equation not mentioned?
Hi a.albreiki. I think I've given you enough code at this point. I can get you started on how you can code the rest (yourself) though:
Code:
with open('ext_data.txt', 'w') as f:
f.write('string')
Oh come on. That's just an if statement.
Code:
4 - also Can I add any Linux command in same python script after finishing the previous steps, such as mv test.txt ../archive/.
Yes you can execute arbitrary external commands. However, you can probably do what you want in straight Python, without the use of external commands. That specifically includes moving files into directories. Look into the following Python modules:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.