Dear Sir,

I would like to extract only unique terms from all sdrf.txt files but this python code outputs unique terms for every file individually. Like Array Data File , Array Design REF ... are repeated in most of sdrf.txt files so i don't wanna print it as unique terms. Could you please tell me to hide case sensitive in python because Characteristics[OrganismPart] is printed as unique term to Characteristics[organism part] similarly for Characteristics[Sex] with Characteristics[sex]. I am eagerly waiting for your support and positive reply.

Regards,
Haobijam

#!/usr/bin/python
import glob
import string

outfile = open('output.txt' , 'w')
files = glob.glob('*.sdrf.txt')
previous = set()
for file in files:
    print('\n'+file)
    infile = open(file)
    #previous = set() # uncomment this if do not need to be unique between the files
    for line in infile:
        lineArray = line.rstrip()
        if not line.startswith('Source Name') : continue
        lineArray = line.split('%s\t')
        output = "%s\t\n"%(lineArray[0])
        outfile.write(output)
        uniqwords = set(word.strip() for word in lineArray[0].split('\t')
                        if word.strip() and word.strip() not in previous) 
        print('The %i unique terms are:\n\t%s' % (len(uniqwords),'\n\t'.join(sorted(uniqwords))))
        previous |=  uniqwords 
    infile.close()
outfile.close()
print('='*80)
print('The %i terms are:\n\t%s' % (len(previous),'\n\t'.join(sorted(previous))))

Dani AI

Generated

A short, practical fix: collect a single global set of column names and compare on a normalized (case- and spacing-insensitive) key instead of the raw strings. The two common problems in the examples are (1) splitting/selection logic that misses or mangles the header, and (2) comparing raw labels so Characteristics[OrganismPart] and Characteristics[organism part] remain distinct. The snippet below builds a canonical key for each label (lowercase, collapse internal whitespace, treat bracketed qualifiers consistently), keeps the first-seen human-readable label for output, and computes per-file frequency so very-common fields can be filtered out.

from pathlib import Path
import re
from collections import Counter

def canonical(label):
    label = label.strip()
    m = re.match(r'^(?P<base>[^\[]+)(?:\[(?P<br>.+)\])?$', label)
    base_tokens = re.findall(r'\w+', (m.group('base') if m else label).lower())
    base_key = '|'.join(base_tokens)
    if m and m.group('br'):
        br_token = ''.join(re.findall(r'\w+', m.group('br').lower()))  # collapse "organism part" -> "organismpart"
        return f"{base_key}|{br_token}" if base_key else br_token
    return base_key

files = list(Path('.').glob('*.sdrf.txt'))
canon_example = {}
docfreq = Counter()

for p in files:
    with p.open(encoding='utf8', errors='replace') as fh:
        # first non-empty line that looks like a header
        header = next((ln for ln in fh if ln.strip() and '\t' in ln), '')
    if not header:
        continue
    cols = header.rstrip('\n').split('\t')
    seen = set()
    for col in cols:
        key = canonical(col)
        seen.add(key)
        canon_example.setdefault(key, col)
    docfreq.update(seen)

# filter out fields that appear in >80% of files
threshold = 0.8 * max(1, len(files))
common = {k for k,v in docfreq.items() if v > threshold}
unique_across_files = [canon_example[k] for k in sorted(canon_example) if k not in common]

for label in unique_across_files:
    print(label)

Notes and cautions: keep the human-readable example (stored in canon_example) so output stays readable while comparisons use the canonical key. Adjust the canonical rules if two different fields are being over-merged (e.g., removing punctuation can collapse meaningful differences). Use encoding='utf8', errors='replace' to avoid crashes on mixed encodings. This approach extends ’s original idea and complements earlier thread suggestions by and while giving a robust, repeatable normalization + frequency-filter workflow.

Recommended Answers

All 3 Replies

Dear Sir,
I have written a python script to parse attributes (i.e. first lines of each sdrf.txt files which is attached here in zip file. But i would also like to extract unique terms from these attributes(output_att.txt) for all sdrf.txt files. Could you please help me.

Regards
Haobijam

#!/usr/bin/python
import glob
#import linecache
outfile = open('output_att.txt' , 'w')
files = glob.glob('*.sdrf.txt')
for file in files:
    infile = open(file)
    #count = 0
    for line in infile:
        
        lineArray = line.rstrip()
        if not line.startswith('Source Name') : continue
        #count = count + 1
        lineArray = line.split('%s\t')
        print lineArray[0]
        output = "%s\t\n"%(lineArray[0])
        outfile.write(output)
    infile.close()
outfile.close()

This thread is duplicate from this one http://www.daniweb.com/forums/thread317912.html see my answer there.

And was copied to bytes.com. At some point you will have to write some of the code yourself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.