473,734 Members | 2,698 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 1703
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
14815
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
1806
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
2654
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
6877
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
5041
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
8799
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
4453
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
2823
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
8777
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9310
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
9237
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
9184
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8187
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...
0
6033
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();...
0
4551
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4813
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2729
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.