473,782 Members | 2,699 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

extracting substrings from a file

Hi,

I have a file with several entries in the form:

AFFX-BioB-5_at E. coli /GEN=bioB /gb:J04423.1 NOTE=SIF
corresponding to nucleotides 2032-2305 of /gb:J04423.1 DEF=E.coli
7,8-diamino-pelargonic acid (bioA), biotin synthetase (bioB),
7-keto-8-amino-pelargonic acid synthetase (bioF), bioC protein, and
dethiobiotin synthetase (bioD), complete cds.

1415785_a_at /gb:NM_009840.1 /DB_XREF=gi:6753 327 /GEN=Cct8 /FEA=FLmRNA
/CNT=482 /TID=Mm.17989.1 /TIER=FL+Stack /STK=281 /UG=Mm.17989 /LL=12469
/DEF=Mus musculus chaperonin subunit 8 (theta) (Cct8), mRNA.
/PROD=chaperonin subunit 8 (theta) /FL=/gb:NM_009840.1 /gb:BC009007.1

and I would like to create a file that has only the following:

AFFX-BioB-5_at /GEN=bioB /gb:J04423.1

1415785_a_at /gb:NM_009840.1 /GEN=Cct8

Could anyone please tell me how can I do it?

Many thanks in advance
Sofia

Sep 11 '06 #1
4 1705
I have a file with several entries in the form:
>
AFFX-BioB-5_at E. coli /GEN=bioB /gb:J04423.1 NOTE=SIF
corresponding to nucleotides 2032-2305 of /gb:J04423.1 DEF=E.coli
7,8-diamino-pelargonic acid (bioA), biotin synthetase (bioB),
7-keto-8-amino-pelargonic acid synthetase (bioF), bioC protein, and
dethiobiotin synthetase (bioD), complete cds.

1415785_a_at /gb:NM_009840.1 /DB_XREF=gi:6753 327 /GEN=Cct8 /FEA=FLmRNA
/CNT=482 /TID=Mm.17989.1 /TIER=FL+Stack /STK=281 /UG=Mm.17989 /LL=12469
/DEF=Mus musculus chaperonin subunit 8 (theta) (Cct8), mRNA.
/PROD=chaperonin subunit 8 (theta) /FL=/gb:NM_009840.1 /gb:BC009007.1

and I would like to create a file that has only the following:

AFFX-BioB-5_at /GEN=bioB /gb:J04423.1

1415785_a_at /gb:NM_009840.1 /GEN=Cct8

Could anyone please tell me how can I do it?
The following seems to do it for me...

outfile = file('out.txt', 'w')
for line in file('in.txt'):
if '/GEN' in line and '/gb:' in line:
newline = []
for index, item in enumerate(line. split()):
if index == 0 or item.startswith ('/GEN')
or item.startswith ('/gb:'):
newline.append( item)
outfile.write(' \t'.join(newlin e))
outfile.write(' \n')
outfile.close()
There are some underdefined conditions...I presume that both the
GEN and gb: have to appear in the line. If only one of them is
required, change the "and" to an "or".

-tkc

Sep 11 '06 #2
so******@gmail. com wrote:
Hi,

I have a file with several entries in the form:

AFFX-BioB-5_at E. coli /GEN=bioB /gb:J04423.1 NOTE=SIF
corresponding to nucleotides 2032-2305 of /gb:J04423.1 DEF=E.coli
7,8-diamino-pelargonic acid (bioA), biotin synthetase (bioB),
7-keto-8-amino-pelargonic acid synthetase (bioF), bioC protein, and
dethiobiotin synthetase (bioD), complete cds.

1415785_a_at /gb:NM_009840.1 /DB_XREF=gi:6753 327 /GEN=Cct8 /FEA=FLmRNA
/CNT=482 /TID=Mm.17989.1 /TIER=FL+Stack /STK=281 /UG=Mm.17989 /LL=12469
/DEF=Mus musculus chaperonin subunit 8 (theta) (Cct8), mRNA.
/PROD=chaperonin subunit 8 (theta) /FL=/gb:NM_009840.1 /gb:BC009007.1

and I would like to create a file that has only the following:

AFFX-BioB-5_at /GEN=bioB /gb:J04423.1

1415785_a_at /gb:NM_009840.1 /GEN=Cct8

Could anyone please tell me how can I do it?

Many thanks in advance
Sofia
Here's my first iteration:
C:\junk>type sofia.py
prefixes = ['/GEN=', '/gb:']

def extract(fname):
f = open(fname, 'r')
chunks = [[]]
for line in f:
words = line.split()
if words:
chunks[-1].extend(words)
else:
chunks.append([])
for chunk in chunks:
if not chunk:
continue
output = [chunk[0]]
for word in chunk:
for prefix in prefixes:
if word.startswith (prefix):
output.append(w ord)
break
print ' '.join(output)

if __name__ == "__main__":
import sys
extract(sys.arg v[1])

C:\junk>sofia.p y sofia.txt
AFFX-BioB-5_at /GEN=bioB /gb:J04423.1 /gb:J04423.1
1415785_a_at /gb:NM_009840.1 /GEN=Cct8 /gb:BC009007.1

Before I fix the duplicate in the first line, you need to say whether
you really want the
/gb:BC009007.1 in the second line thrown away -- IOW, what's the rule?
For each prefix, either (1) get the first "word" that starts with that
prefix or (2) get all unique such words. You choose.

Cheers,
John

Sep 11 '06 #3
so******@gmail. com wrote:
Hi,

I have a file with several entries in the form:

AFFX-BioB-5_at E. coli /GEN=bioB /gb:J04423.1 NOTE=SIF
corresponding to nucleotides 2032-2305 of /gb:J04423.1 DEF=E.coli
7,8-diamino-pelargonic acid (bioA), biotin synthetase (bioB),
7-keto-8-amino-pelargonic acid synthetase (bioF), bioC protein, and
dethiobiotin synthetase (bioD), complete cds.

1415785_a_at /gb:NM_009840.1 /DB_XREF=gi:6753 327 /GEN=Cct8 /FEA=FLmRNA
/CNT=482 /TID=Mm.17989.1 /TIER=FL+Stack /STK=281 /UG=Mm.17989 /LL=12469
/DEF=Mus musculus chaperonin subunit 8 (theta) (Cct8), mRNA.
/PROD=chaperonin subunit 8 (theta) /FL=/gb:NM_009840.1 /gb:BC009007.1

and I would like to create a file that has only the following:

AFFX-BioB-5_at /GEN=bioB /gb:J04423.1

1415785_a_at /gb:NM_009840.1 /GEN=Cct8

Could anyone please tell me how can I do it?

Many thanks in advance
Sofia
What have your tried so far?

Hint: split line on spaces, the first pieces is the first item you want,
then iterate over the pieces looking for the /GEN and /gb: pieces that
you are interested in keeping. I am assuming that /GEN= and /gb: data
doesn't have any spaces in them. If they do, you will need to use
regular expressions instead of split.

-Larry Bates
Sep 11 '06 #4
<so******@gmail .comwrote in message
news:11******** ************@p7 9g2000cwp.googl egroups.com...
Hi,

I have a file with several entries in the form:

AFFX-BioB-5_at E. coli /GEN=bioB /gb:J04423.1 NOTE=SIF
corresponding to nucleotides 2032-2305 of /gb:J04423.1 DEF=E.coli
7,8-diamino-pelargonic acid (bioA), biotin synthetase (bioB),
7-keto-8-amino-pelargonic acid synthetase (bioF), bioC protein, and
dethiobiotin synthetase (bioD), complete cds.

1415785_a_at /gb:NM_009840.1 /DB_XREF=gi:6753 327 /GEN=Cct8 /FEA=FLmRNA
/CNT=482 /TID=Mm.17989.1 /TIER=FL+Stack /STK=281 /UG=Mm.17989 /LL=12469
/DEF=Mus musculus chaperonin subunit 8 (theta) (Cct8), mRNA.
/PROD=chaperonin subunit 8 (theta) /FL=/gb:NM_009840.1 /gb:BC009007.1

and I would like to create a file that has only the following:

AFFX-BioB-5_at /GEN=bioB /gb:J04423.1

1415785_a_at /gb:NM_009840.1 /GEN=Cct8
Here's a pyparsing solution that will address your immediate question, and
also gives you some leeway for adding other "/" options to your search.
Pyparsing's home page is at pyparsing.wikis paces.com.

-- Paul
data = """
AFFX-BioB-5_at E. coli /GEN=bioB /gb:J04423.1 NOTE=SIF
corresponding to nucleotides 2032-2305 of /gb:J04423.1 DEF=E.coli
7,8-diamino-pelargonic acid (bioA), biotin synthetase (bioB),
7-keto-8-amino-pelargonic acid synthetase (bioF), bioC protein, and
dethiobiotin synthetase (bioD), complete cds.

1415785_a_at /gb:NM_009840.1 /DB_XREF=gi:6753 327 /GEN=Cct8 /FEA=FLmRNA
/CNT=482 /TID=Mm.17989.1 /TIER=FL+Stack /STK=281 /UG=Mm.17989 /LL=12469
/DEF=Mus musculus chaperonin subunit 8 (theta) (Cct8), mRNA.
/PROD=chaperonin subunit 8 (theta) /FL=/gb:NM_009840.1 /gb:BC009007.1
"""

from pyparsing import *

# create expression we are looking for:
# name [ junk word... ] /qualifier...
name = Word(alphanums, printables).set ResultsName("na me")
junkWord = ~(Literal("/")) + Word(printables )
qualifier = ("/" + Word(alphas+"_-.").setResultsN ame("key") + \
oneOf("= :") + \
Word(printables ).setResultsNam e("value"))
expr = name + ZeroOrMore(junk Word) + \
Dict(ZeroOrMore (qualifier)).se tResultsName("q uals")

# use parse action to repackage qualifier data to support "dict"-like
# access to qualifiers
qualifier.setPa rseAction( lambda t: (t.key,"".join( t)) )

# use this parse action instead if you just want whatever is
# after the '=' or ':' delimiter in the qualifier
# qualifier.setPa rseAction( lambda t: (t.key,t.value) )

# parse data strings, showing returned data structure
# (just to show what pyparsing results structure looks like)
for d in data.split("\n\ n"):
res = expr.parseStrin g(d)
print res.dump()
print
print

# now just do what the OP wanted in the first place
for d in data.split("\n\ n"):
res = expr.parseStrin g(d)
print res.name, res.quals["gb"], res.quals["GEN"]
Gives these results:
['AFFX-BioB-5_at', 'E.', 'coli', [('GEN', '/GEN=bioB'), ('gb',
'/gb:J04423.1')]]
- name: AFFX-BioB-5_at
- quals: [('GEN', '/GEN=bioB'), ('gb', '/gb:J04423.1')]
- GEN: /GEN=bioB
- gb: /gb:J04423.1

['1415785_a_at', [('gb', '/gb:NM_009840.1' ), ('DB_XREF',
'/DB_XREF=gi:6753 327'), ('GEN', '/GEN=Cct8'), ('FEA', '/FEA=FLmRNA'),
('CNT', '/CNT=482'), ('TID', '/TID=Mm.17989.1' ), ('TIER', '/TIER=FL+Stack') ,
('STK', '/STK=281'), ('UG', '/UG=Mm.17989'), ('LL', '/LL=12469'), ('DEF',
'/DEF=Mus')]]
- name: 1415785_a_at
- quals: [('gb', '/gb:NM_009840.1' ), ('DB_XREF', '/DB_XREF=gi:6753 327'),
('GEN', '/GEN=Cct8'), ('FEA', '/FEA=FLmRNA'), ('CNT', '/CNT=482'), ('TID',
'/TID=Mm.17989.1' ), ('TIER', '/TIER=FL+Stack') , ('STK', '/STK=281'), ('UG',
'/UG=Mm.17989'), ('LL', '/LL=12469'), ('DEF', '/DEF=Mus')]
- CNT: /CNT=482
- DB_XREF: /DB_XREF=gi:6753 327
- DEF: /DEF=Mus
- FEA: /FEA=FLmRNA
- GEN: /GEN=Cct8
- LL: /LL=12469
- STK: /STK=281
- TID: /TID=Mm.17989.1
- TIER: /TIER=FL+Stack
- UG: /UG=Mm.17989
- gb: /gb:NM_009840.1
AFFX-BioB-5_at /gb:J04423.1 /GEN=bioB
1415785_a_at /gb:NM_009840.1 /GEN=Cct8
Sep 11 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2538
by: Avi | last post by:
hi, Can anyone tell me what the problem is and how to solve it The following piece of code resides on an asp page on the server and is used to download files from the server to the machine accessing the abobe mentioned asp page. It WORKS for every type of file when I change the content type according to the file type, but it won't work with self extracting files. When an end user downloads a self extracting file by accessing the...
7
14816
by: cpp_weenie | last post by:
Given a std::string of the form "default(N)" where N is an integer number of any length (e.g. the literal string might be "default(243)"), what is the quickest way to extract the characters representing the integer into another std::string? In the example above, I'd want to end up with a std:string whose value is "243". The substrings "default(" and ")" are invariant - they're always present in the string I have to work with. ...
9
1807
by: C3 | last post by:
I have to process some data in C that is given to me as a char * array. I have a fairly large number of substrings (well, they're not actually printable, but let's treat them as strings) that I have to search for in the data. I need to keep a count of how often each of these substrings occurs in my original data and then print it out at the end. This is a fairly mundane task, but since I have so many substrings, it's a pain having to...
3
2655
by: War Eagle | last post by:
I've been looking at .substring and .trim methods and I still have a question about extracting substrings from a textbox. Basically the textbox contains the full path to a file ... for example C:\testfile.txt or ... C:\download\temp\dlls\testfile.dll I want to be able to extract the file name from this textbox (and put it in a string) when I click a button. Can someone illustrate how to write this line of code?
5
6879
by: ORC | last post by:
Is there an easy way to extract a number from a string like: result = ExtractNumber("this is a 4 string"); which should give the result = 4; Thanks Ole
8
5049
by: girish | last post by:
Hi, I want to generate all non-empty substrings of a string of length >=2. Also, each substring is to be paired with 'string - substring' part and vice versa. Thus, gives me , , , , , ] etc. Similarly, 'abcd' should give me , , , , , ,, , , , , , ,] I've tried the following but i cant prevent duplicates and i'm missing
4
8802
by: ashilyas | last post by:
Hi all, I am new to this forum as well as Visual Basic. I haven't been able to find a resource that tells me what functions are available in Visual Basic like you can find the listing in C++ and java. If someone can tell me how to get that it would be great. My question though is, I have a string variable in my VB code that has a long string (a combination of smaller strings seperated by ";") I need to extract all theses...
6
4454
by: Werner | last post by:
Hi, I try to read (and extract) some "self extracting" zipefiles on a Windows system. The standard module zipefile seems not to be able to handle this. False Is there a wrapper or has some one experience with other libaries to
2
2827
by: Pilcrow | last post by:
This problem was raised in comp.lang.perl.misc, and the poster was concerned, among other things, by the speed of execution. Since C is faster than perl, I wonder how a C coder would solve it? Given a *very* long string, A, and a shorter string, B, extract all substrings of A that differ from B in at most N positions. For example: N = 2 A = 'abcdefaacdefxbcxfaaabcdefaaaacdxf'
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10308
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10143
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10076
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8964
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7486
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6729
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4040
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2870
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.