コード例 #1
0
ファイル: Word.py プロジェクト: WileESpaghetti/learn-yupik
def apostrophePurpose(word):
	"""is the apostrophe being used for gemination, separate 'n' and 'g', etc."""
	exp = Base.explode(word)
	purpose = -1
	for i in range(len(exp)):
		if i > 0 and exp[i] == '\'':
			if i < len(exp) - 1:
				if Alphabet.isVowel(exp[i - 1]):
					if Alphabet.isVowel(exp[i + 1]):
						purpose = APOS_PREVENT_GEMMINATION
						break
					elif exp[i + 1] == 'r':
						purpose = APOS_DISRUPT_STRESS
						break
				else:
					if Alphabet.isVowel(exp[i + 1]):
						purpose = APOS_GEMINATION_MARKER
						break
					elif exp[i - 1] == 'n' and exp[i + 1] == 'g':
						purpose = APOS_NG_SEPARATOR
						break
					else:
						# FIXME need to test if a catch-all is appropriate. technically the only
						# other valid use of a \' is whenever auto-devoicing occurs. (stop + nasal || fric)
						#FIXME need to do research on autodevoicing to make sure this ^^ is acurate
						# FIXME will need to write a test to make sure cases without auto devoicing are not matched
						purpose = APOS_PREVENT_DEVOICING
						break
			else:
				purpose = APOS_SHORT_WORD
	return purpose
コード例 #2
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
    def back_transcribe(self):
        """Returns the DNA sequence from an RNA sequence. New Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG", \
                                IUPAC.unambiguous_rna)
        >>> messenger_rna
        Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
        >>> messenger_rna.back_transcribe()
        Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())

        Trying to back-transcribe a protein or DNA sequence raises an
        exception.

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.back_transcribe()
        Traceback (most recent call last):
           ...
        ValueError: Proteins cannot be back transcribed!
        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins cannot be back transcribed!")
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.DNAAlphabet):
            raise ValueError("DNA cannot be back transcribed!")

        if self.alphabet == IUPAC.unambiguous_rna:
            alphabet = IUPAC.unambiguous_dna
        elif self.alphabet == IUPAC.ambiguous_rna:
            alphabet = IUPAC.ambiguous_dna
        else:
            alphabet = Alphabet.generic_dna
        return Seq(str(self).replace("U", "T").replace("u", "t"), alphabet)
コード例 #3
0
def getSyllables(word):
    """ return a list of the syllables that make up word """
    syllables = []
    syl = []
    exp = Base.explode(word)

    for i in range(len(exp)):
        c = exp[i]
        syl.append(c)
        if i < len(exp) - 1:
            if Alphabet.isConsonant(c) and Alphabet.isConsonant(exp[i + 1]):
                syllables.append(syl)
                syl = []
    syllables.append(syl)

    syl = []
    syl2 = []
    for s in syllables:
        for i in range(len(s)):
            if Alphabet.isConsonant(s[i]) and (i > 0 and i < len(s) - 1):
                if Alphabet.isVowel(s[i - 1]) and Alphabet.isVowel(s[i + 1]):
                    syl2.append(syl)
                    syl = []
            syl.append(s[i])
        syl2.append(syl)
        syl = []
    return syl2
コード例 #4
0
def getSyllables(word):
	""" return a list of the syllables that make up word """
	syllables = []
	syl = []
	exp = Base.explode(word)

	for i in range(len(exp)):
		c = exp[i]
		syl.append(c)
		if i < len(exp) - 1:
			if Alphabet.isConsonant(c) and Alphabet.isConsonant(exp[i + 1]):
				syllables.append(syl)
				syl = []
	syllables.append(syl)

	syl = []
	syl2 = []
	for s in syllables:
		for i in range(len(s)):
			if Alphabet.isConsonant(s[i]) and (i > 0 and i < len(s) - 1):
				if Alphabet.isVowel(s[i - 1]) and Alphabet.isVowel(s[i + 1]):
					syl2.append(syl)
					syl = []
			syl.append(s[i])
		syl2.append(syl)
		syl = []
	return syl2
コード例 #5
0
ファイル: Seq.py プロジェクト: nuin/biopython
    def back_transcribe(self):
        """Returns the DNA sequence from an RNA sequence. New Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG", \
                                IUPAC.unambiguous_rna)
        >>> messenger_rna
        Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
        >>> messenger_rna.back_transcribe()
        Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())

        Trying to back-transcribe a protein or DNA sequence raises an
        exception.

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.back_transcribe()
        Traceback (most recent call last):
           ...
        ValueError: Proteins cannot be back transcribed!
        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet) :
            raise ValueError("Proteins cannot be back transcribed!")
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.DNAAlphabet) :
            raise ValueError("DNA cannot be back transcribed!")

        if self.alphabet==IUPAC.unambiguous_rna:
            alphabet = IUPAC.unambiguous_dna
        elif self.alphabet==IUPAC.ambiguous_rna:
            alphabet = IUPAC.ambiguous_dna
        else:
            alphabet = Alphabet.generic_dna
        return Seq(str(self).replace("U", "T").replace("u", "t"), alphabet)
コード例 #6
0
ファイル: output.py プロジェクト: Monish-Samuel/CICD-pipeline
def run_code():
    string = request.form['string']
    char = request.form['character']
    leng = Alphabet.word_length(string)
    matching = Alphabet.matching_char(string, char)
    palin = Alphabet.palindrome_or_not(string)
    rever = Alphabet.reverse(string)
    return render_template('pass.html', l=leng, m=matching, p=palin, r=rever)
コード例 #7
0
    def test_matching_char(self):
        sent1 = Alphabet.matching_char("Hi everyone my name is Monish", 'o')
        self.assertEqual(sent1,
                         'No. of o in "Hi everyone my name is Monish" is 2')

        sent2 = Alphabet.matching_char("Hi everyone my name is Oswald", 'O')
        self.assertEqual(sent2,
                         'No. of O in "Hi everyone my name is Oswald" is 1')
コード例 #8
0
ファイル: Game.py プロジェクト: SahinEgilmez/AR-Word-Game
    def setPlayer(self, count):  # set player number and get questions according to this.
        self.count = count
        self.alphabet = Alphabet(count)

        self.currentQuestion = self.alphabet.getQuestion()
        for i in range(0, count):
            self.faces[i] = Face(i, None)
            self.faceTrackers[i] = None
            if(self.faces[i].letter is None):
                self.faces[i].letter = self.currentQuestion.answer[i]
コード例 #9
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
 def __radd__(self, other):
     if hasattr(other, "alphabet"):
         #other should be a Seq or a MutableSeq
         if not Alphabet._check_type_compatible(
             [self.alphabet, other.alphabet]):
             raise TypeError("Incompatable alphabets %s and %s" \
                             % (repr(self.alphabet), repr(other.alphabet)))
         #They should be the same sequence type (or one of them is generic)
         a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
         return self.__class__(str(other) + str(self), a)
     elif isinstance(other, basestring):
         #other is a plain string - use the current alphabet
         return self.__class__(other + str(self), self.alphabet)
     else:
         raise TypeError
コード例 #10
0
ファイル: Seq.py プロジェクト: nuin/biopython
 def __radd__(self, other):
     if hasattr(other, "alphabet") :
         #other should be a Seq or a MutableSeq
         if not Alphabet._check_type_compatible([self.alphabet,
                                                 other.alphabet]) :
             raise TypeError("Incompatable alphabets %s and %s" \
                             % (repr(self.alphabet), repr(other.alphabet)))
         #They should be the same sequence type (or one of them is generic)
         a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
         return self.__class__(str(other) + str(self), a)
     elif isinstance(other, basestring) :
         #other is a plain string - use the current alphabet
         return self.__class__(other + str(self), self.alphabet)
     else :
         raise TypeError
コード例 #11
0
def syllableMatches(syl, form):
    """ eg. syllableMatches('rte', '[V]VCe')
	capital 'V' or 'C' match vowels and consonants respectively
	letters in []'s shows optional letters. checks from the end of the word"""
    # FIXME this is not necessarily done on a syllable by syllable basis. sometimes it
    # can overlap boundaries
    sylMatches = False

    # better handling of 'ng' and other double letters
    syl = Base.explode(syl)
    form = Base.explode(form)

    syl = syl[::-1]
    form = form[::-1]

    #FIXME need to write test about if form longer than syl has correct behavior
    #FIXME optional '[]' letters should not increment i
    inBrackets = False
    j = 0

    if len(syl) > 0 and len(syl) >= len(form):
        for i in range(len(form)):
            if i <= j:
                if inBrackets:
                    # FIXME not sure if there is really anything to do but ignore
                    if form[i] == '[':
                        inBrackets = False
                        j += 1
                else:
                    if form[i] == 'V' and Alphabet.isVowel(syl[j]):
                        sylMatches = True
                        j += 1
                    elif form[i] == 'C' and Alphabet.isConsonant(syl[j]):
                        sylMatches = True
                        j += 1
                    elif form[i] == syl[j]:
                        #FIXME this may have some false positives
                        sylMatches = True
                        j += 1
                    elif form[i] == ']':
                        # we are reversed, so close brackets = open brackets
                        inBrackets = True
                    else:
                        sylMatches = False
                        break
            else:
                break
    return sylMatches
コード例 #12
0
def syllableMatches(syl, form):
	""" eg. syllableMatches('rte', '[V]VCe')
	capital 'V' or 'C' match vowels and consonants respectively
	letters in []'s shows optional letters. checks from the end of the word"""
	# FIXME this is not necessarily done on a syllable by syllable basis. sometimes it
	# can overlap boundaries
	sylMatches = False

	# better handling of 'ng' and other double letters
	syl = Base.explode(syl)
	form = Base.explode(form)

	syl = syl[::-1]
	form = form[::-1]

	#FIXME need to write test about if form longer than syl has correct behavior
	#FIXME optional '[]' letters should not increment i
	inBrackets = False
	j = 0

	if len(syl) > 0 and len(syl) >= len(form):
		for i in range(len(form)):
			if i <= j:
				if inBrackets:
					# FIXME not sure if there is really anything to do but ignore
					if form[i] == '[':
						inBrackets = False
						j += 1
				else:
					if form[i] == 'V' and Alphabet.isVowel(syl[j]):
						sylMatches = True
						j += 1
					elif form[i] == 'C' and Alphabet.isConsonant(syl[j]):
						sylMatches = True
						j += 1
					elif form[i] == syl[j]:
						#FIXME this may have some false positives
						sylMatches = True
						j += 1
					elif form[i] == ']':
						# we are reversed, so close brackets = open brackets
						inBrackets = True
					else:
						sylMatches = False
						break
			else:
				break
	return sylMatches
コード例 #13
0
ファイル: Base.py プロジェクト: WileESpaghetti/learn-yupik
def explode(word):
	""" split the word into it's letters. this makes working with letters made up
	of more than one character (eg. 'll' or 'ng' a whole lot easier """
	#FIXME should \' be treated as a separate letter or combined with the letter
	# it is telling to geminate (eg. r') or completely omited in the output
	#FIXME needs to throw exception if incorrect character found
	exploded = []

	for i in word:
		# test if a letter is a valid doubled letter or is 'ng'
		if len(exploded) > 0 and Alphabet.isADouble(i) and exploded[-1] == i:
			exploded[-1] = i + i
		elif len(exploded) > 0 and exploded[-1] == 'n' and i == 'g':
			exploded[-1] = 'ng'
		elif len(exploded) > 0 and exploded[-1] == 'ń'  and i == 'g':
			exploded[-1] = 'ńg'
		elif len(exploded) > 0 and exploded[-1] + i == 'ḿ':
			exploded[-1] = 'ḿ'
		elif len(exploded) > 0 and exploded[-1] + i == 'ń':
			exploded[-1] = 'ń'
		elif len(exploded) > 0 and (i == '\xe1' or i == '\xb8' or i == '\xbf' or i == '\xc5' or i == '\x84'):
			if (exploded[-1] == '\xe1' or exploded[-1] == '\xb8' or exploded[-1] == '\xbf' or exploded[-1] == '\xc5' or exploded[-1] == '\x84'):
				exploded[-1] = exploded[-1] + i
			else:
				exploded.append(i)
		else:
			exploded.append(i)
	return exploded
コード例 #14
0
ファイル: Word.py プロジェクト: WileESpaghetti/learn-yupik
def getAutoGemminationPattern(word):
	gempat = []
	exp = Base.explode(word)
	rl = getRhythmicVowelLengthPattern(word)
	for i in range(len(exp)):
		if i > 0 and i < len(exp) - 2:
			if Alphabet.isVowel(exp[i - 1]) and Alphabet.isConsonant(exp[i]) and Alphabet.isVowel(
					exp[i + 1]) and Alphabet.isVowel(exp[i + 2]):
				gempat.append(True)
			else:
				gempat.append(False)
		elif i > 0 and exp[i - 1] == 'e' and hasRhythmicLength(word, i - 1):
			gempat.append(True)
		else:
			gempat.append(False)
	return gempat
コード例 #15
0
ファイル: Seq.py プロジェクト: nuin/biopython
    def __cmp__(self, other):
        """Compare the sequence for to another sequence or a string.

        If compared to another sequence the alphabets must be compatible.
        Comparing DNA to RNA, or Nucleotide to Protein will raise an
        exception.

        Otherwise only the sequence itself is compared, not the precise
        alphabet.

        This method indirectly supports ==, < , etc."""
        if hasattr(other, "alphabet") :
            #other should be a Seq or a MutableSeq
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]) :
                raise TypeError("Incompatable alphabets %s and %s" \
                                % (repr(self.alphabet), repr(other.alphabet)))
            #They should be the same sequence type (or one of them is generic)
            if isinstance(other, MutableSeq):
                #See test_GAQueens.py for an historic usage of a non-string
                #alphabet!  Comparing the arrays supports this.
                return cmp(self.data, other.data)
            else :
                return cmp(str(self), str(other))
        elif isinstance(other, basestring) :
            return cmp(str(self), other)
        else :
            raise TypeError
コード例 #16
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
    def __cmp__(self, other):
        """Compare the sequence for to another sequence or a string.

        If compared to another sequence the alphabets must be compatible.
        Comparing DNA to RNA, or Nucleotide to Protein will raise an
        exception.

        Otherwise only the sequence itself is compared, not the precise
        alphabet.

        This method indirectly supports ==, < , etc."""
        if hasattr(other, "alphabet"):
            #other should be a Seq or a MutableSeq
            if not Alphabet._check_type_compatible(
                [self.alphabet, other.alphabet]):
                raise TypeError("Incompatable alphabets %s and %s" \
                                % (repr(self.alphabet), repr(other.alphabet)))
            #They should be the same sequence type (or one of them is generic)
            if isinstance(other, MutableSeq):
                #See test_GAQueens.py for an historic usage of a non-string
                #alphabet!  Comparing the arrays supports this.
                return cmp(self.data, other.data)
            else:
                return cmp(str(self), str(other))
        elif isinstance(other, basestring):
            return cmp(str(self), other)
        else:
            raise TypeError
コード例 #17
0
def explode(word):
    """ split the word into it's letters. this makes working with letters made up
	of more than one character (eg. 'll' or 'ng' a whole lot easier """
    #FIXME should \' be treated as a separate letter or combined with the letter
    # it is telling to geminate (eg. r') or completely omited in the output
    #FIXME needs to throw exception if incorrect character found
    exploded = []

    for i in word:
        # test if a letter is a valid doubled letter or is 'ng'
        if len(exploded) > 0 and Alphabet.isADouble(i) and exploded[-1] == i:
            exploded[-1] = i + i
        elif len(exploded) > 0 and exploded[-1] == 'n' and i == 'g':
            exploded[-1] = 'ng'
        elif len(exploded) > 0 and exploded[-1] == 'ń' and i == 'g':
            exploded[-1] = 'ńg'
        elif len(exploded) > 0 and exploded[-1] + i == 'ḿ':
            exploded[-1] = 'ḿ'
        elif len(exploded) > 0 and exploded[-1] + i == 'ń':
            exploded[-1] = 'ń'
        elif len(exploded) > 0 and (i == '\xe1' or i == '\xb8' or i == '\xbf'
                                    or i == '\xc5' or i == '\x84'):
            if (exploded[-1] == '\xe1' or exploded[-1] == '\xb8'
                    or exploded[-1] == '\xbf' or exploded[-1] == '\xc5'
                    or exploded[-1] == '\x84'):
                exploded[-1] = exploded[-1] + i
            else:
                exploded.append(i)
        else:
            exploded.append(i)
    return exploded
コード例 #18
0
def genBtn(root, x_inc):
    btn_x_coord = 0
    btn_list = []
    for char in alpha.getUpper():
        btn = makeBtn(root, char, 2, 5)
        btn.place(x=btn_x_coord, y=10)
        btn_list.append(btn)
        btn_x_coord += x_inc
    return btn_list
コード例 #19
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
 def __radd__(self, other):
     if hasattr(other, "alphabet"):
         #other should be a Seq or a MutableSeq
         if not Alphabet._check_type_compatible(
             [self.alphabet, other.alphabet]):
             raise TypeError("Incompatable alphabets %s and %s" \
                             % (repr(self.alphabet), repr(other.alphabet)))
         #They should be the same sequence type (or one of them is generic)
         a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
         if isinstance(other, MutableSeq):
             #See test_GAQueens.py for an historic usage of a non-string
             #alphabet!  Adding the arrays should support this.
             return self.__class__(other.data + self.data, a)
         else:
             return self.__class__(str(other) + str(self), a)
     elif isinstance(other, basestring):
         #other is a plain string - use the current alphabet
         return self.__class__(str(other) + str(self), self.alphabet)
     else:
         raise TypeError
コード例 #20
0
ファイル: Seq.py プロジェクト: nuin/biopython
 def __radd__(self, other):
     if hasattr(other, "alphabet") :
         #other should be a Seq or a MutableSeq
         if not Alphabet._check_type_compatible([self.alphabet,
                                                 other.alphabet]) :
             raise TypeError("Incompatable alphabets %s and %s" \
                             % (repr(self.alphabet), repr(other.alphabet)))
         #They should be the same sequence type (or one of them is generic)
         a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
         if isinstance(other, MutableSeq):
             #See test_GAQueens.py for an historic usage of a non-string
             #alphabet!  Adding the arrays should support this.
             return self.__class__(other.data + self.data, a)
         else :
             return self.__class__(str(other) + str(self), a)
     elif isinstance(other, basestring) :
         #other is a plain string - use the current alphabet
         return self.__class__(str(other) + str(self), self.alphabet)
     else :
         raise TypeError
コード例 #21
0
ファイル: Seq.py プロジェクト: nuin/biopython
    def complement(self):
        """Returns the complement sequence. New Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> my_dna = Seq("CCCCCGATAG", IUPAC.unambiguous_dna)
        >>> my_dna
        Seq('CCCCCGATAG', IUPACUnambiguousDNA())
        >>> my_dna.complement()
        Seq('GGGGGCTATC', IUPACUnambiguousDNA())

        Trying to complement a protein sequence raises an exception.

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.complement()
        Traceback (most recent call last):
           ...
        ValueError: Proteins do not have complements!
        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet) :
            raise ValueError("Proteins do not have complements!")
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.DNAAlphabet) :
            d = ambiguous_dna_complement
        elif isinstance(Alphabet._get_base_alphabet(self.alphabet),
                        Alphabet.RNAAlphabet) :
            d = ambiguous_rna_complement
        elif 'U' in self._data and 'T' in self._data:
            #TODO - Handle this cleanly?
            raise ValueError("Mixed RNA/DNA found")
        elif 'U' in self._data:
            d = ambiguous_rna_complement
        else:
            d = ambiguous_dna_complement
        ttable = self.__maketrans(d)
        #Much faster on really long sequences than the previous loop based one.
        #thx to Michael Palmer, University of Waterloo
        s = str(self).translate(ttable)
        return Seq(s, self.alphabet)
コード例 #22
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
    def complement(self):
        """Returns the complement sequence. New Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> my_dna = Seq("CCCCCGATAG", IUPAC.unambiguous_dna)
        >>> my_dna
        Seq('CCCCCGATAG', IUPACUnambiguousDNA())
        >>> my_dna.complement()
        Seq('GGGGGCTATC', IUPACUnambiguousDNA())

        Trying to complement a protein sequence raises an exception.

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.complement()
        Traceback (most recent call last):
           ...
        ValueError: Proteins do not have complements!
        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins do not have complements!")
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.DNAAlphabet):
            d = ambiguous_dna_complement
        elif isinstance(Alphabet._get_base_alphabet(self.alphabet),
                        Alphabet.RNAAlphabet):
            d = ambiguous_rna_complement
        elif 'U' in self._data and 'T' in self._data:
            #TODO - Handle this cleanly?
            raise ValueError("Mixed RNA/DNA found")
        elif 'U' in self._data:
            d = ambiguous_rna_complement
        else:
            d = ambiguous_dna_complement
        ttable = self.__maketrans(d)
        #Much faster on really long sequences than the previous loop based one.
        #thx to Michael Palmer, University of Waterloo
        s = str(self).translate(ttable)
        return Seq(s, self.alphabet)
コード例 #23
0
def lSyllableMatches(syl, form):
    """ eg. syllableMatches('rte', '[V]VCe')
	capital 'V' or 'C' match vowels and consonants respectivly
	letters in []'s shows optional letters. checks from the start of the word"""
    # FIXME this is not necessarily done on a syllable by syllable basis. sometimes it
    # can overlap boundaries
    sylMatches = False

    # better handling of 'ng' and other double letters
    syl = Base.explode(syl)
    form = Base.explode(form)

    if len(syl) > 0:
        inBrackets = False
        j = 0
        for i in range(len(form)):
            if inBrackets:
                # FIXME not sure if there is really anything to do but ignore
                if form[i] == '[':
                    inBrackets = False
                    j += 1
            else:
                if form[i] == 'V' and Alphabet.isVowel(syl[j]):
                    sylMatches = True
                    j += 1
                elif form[i] == 'C' and Alphabet.isConsonant(syl[j]):
                    sylMatches = True
                    j += 1
                elif form[i] == syl[j]:
                    #FIXME this may have some false positives
                    sylMatches = True
                    j += 1
                elif form[i] == ']':
                    # we are reversed, so close brackets = open brackets
                    inBrackets = True
                else:
                    sylMatches = False
                    break
    return sylMatches
コード例 #24
0
def lSyllableMatches(syl, form):
	""" eg. syllableMatches('rte', '[V]VCe')
	capital 'V' or 'C' match vowels and consonants respectivly
	letters in []'s shows optional letters. checks from the start of the word"""
	# FIXME this is not necessarily done on a syllable by syllable basis. sometimes it
	# can overlap boundaries
	sylMatches = False

	# better handling of 'ng' and other double letters
	syl = Base.explode(syl)
	form = Base.explode(form)

	if len(syl) > 0:
		inBrackets = False
		j = 0
		for i in range(len(form)):
			if inBrackets:
				# FIXME not sure if there is really anything to do but ignore
				if form[i] == '[':
					inBrackets = False
					j += 1
			else:
				if form[i] == 'V' and Alphabet.isVowel(syl[j]):
					sylMatches = True
					j += 1
				elif form[i] == 'C' and Alphabet.isConsonant(syl[j]):
					sylMatches = True
					j += 1
				elif form[i] == syl[j]:
					#FIXME this may have some false positives
					sylMatches = True
					j += 1
				elif form[i] == ']':
					# we are reversed, so close brackets = open brackets
					inBrackets = True
				else:
					sylMatches = False
					break
	return sylMatches
コード例 #25
0
ファイル: HangmanWIthPyGame.py プロジェクト: CAt0mIcS/Python3
def getBtns():
    x_coord = 10
    iteration = 0
    btn_lst = []
    for itr, char in enumerate(alpha.getUpper()):
        if itr < 13:
            btn = Button(0, 255, 0, x_coord, 10, 40, 40, char)
            btn_lst.append(btn)
            x_coord += 70
        if itr > 12:
            if iteration == 0:
                x_coord = 10
                iteration = 1
            btn = Button(0, 255, 0, x_coord, 80, 40, 40, char)
            btn_lst.append(btn)
            x_coord += 70
    return btn_lst  # return lbl_list
コード例 #26
0
ファイル: Word.py プロジェクト: WileESpaghetti/learn-yupik
def isVoiced(word, c):
	"""test position c to see if it is voiced"""
	# FIXME does not properly handle if char other than a stop or fricative is found at 'c'
	voiced = True
	exp = Base.explode(word)
	l = exp[c]
	if c == 0 and l == 's':
		voiced = False
	elif c == len(exp) - 1 and l == 'r':
		voiced = False
	elif Alphabet.isVoicelessFricative(l):
		voiced = False
	elif Alphabet.isVoicelessNasal(l):
		voiced = False
	elif Alphabet.isVoicedFricative(l):
		if c > 0 and (Alphabet.isVoicelessFricative(exp[c - 1]) or Alphabet.isStop(exp[c - 1])):
			voiced = False
		elif c < len(exp) - 1 and Alphabet.isStop(exp[c + 1]):
			voiced = False
	elif Alphabet.isVoicedNasal(l) and c > 0 and (
		Alphabet.isVoicelessFricative(exp[c - 1]) or Alphabet.isStop(exp[c - 1])):
		voiced = False

	return voiced
コード例 #27
0
ファイル: Seq.py プロジェクト: nuin/biopython
    def _get_seq_str_and_check_alphabet(self, other_sequence) :
        """string/Seq/MutableSeq to string, checking alphabet (PRIVATE).

        For a string argument, returns the string.

        For a Seq or MutableSeq, it checks the alphabet is compatible
        (raising an exception if it isn't), and then returns a string.
        """
        try :
            other_alpha = other_sequence.alphabet
        except AttributeError :
            #Assume other_sequence is a string
            return other_sequence

        #Other should be a Seq or a MutableSeq
        if not Alphabet._check_type_compatible([self.alphabet, other_alpha]) :
            raise TypeError("Incompatable alphabets %s and %s" \
                            % (repr(self.alphabet), repr(other_alpha)))
        #Return as a string
        return str(other_sequence)
コード例 #28
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
    def _get_seq_str_and_check_alphabet(self, other_sequence):
        """string/Seq/MutableSeq to string, checking alphabet (PRIVATE).

        For a string argument, returns the string.

        For a Seq or MutableSeq, it checks the alphabet is compatible
        (raising an exception if it isn't), and then returns a string.
        """
        try:
            other_alpha = other_sequence.alphabet
        except AttributeError:
            #Assume other_sequence is a string
            return other_sequence

        #Other should be a Seq or a MutableSeq
        if not Alphabet._check_type_compatible([self.alphabet, other_alpha]):
            raise TypeError("Incompatable alphabets %s and %s" \
                            % (repr(self.alphabet), repr(other_alpha)))
        #Return as a string
        return str(other_sequence)
コード例 #29
0
def initialize():
    global btn_list
    program = App(root)

    # App.draw_hangman()
    panel = Label(root, height=350, width=450, image=img_list[0])
    panel.place(x=425, y=60)

    #create all buttons :)
    btn_x_coord = 0
    btn_list = []
    for char in alpha.getLower():
        btn = App.make_btn(program, char, 2, 5)
        btn.pack()
        btn.place(x=btn_x_coord, y=10)
        btn_list.append(btn)
        btn_x_coord += 50

    #Set location and size of window and initialize it
    root.geometry('1295x500+10+10')
    root.mainloop()
コード例 #30
0
ファイル: Seq.py プロジェクト: nuin/biopython
    def complement(self):
        """Modify the mutable sequence to take on its complement.

        Trying to complement a protein sequence raises an exception.

        No return value"""
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet) :
            raise ValueError("Proteins do not have complements!")
        if self.alphabet in (IUPAC.ambiguous_dna, IUPAC.unambiguous_dna):
            d = ambiguous_dna_complement
        elif self.alphabet in (IUPAC.ambiguous_rna, IUPAC.unambiguous_rna):
            d = ambiguous_rna_complement
        elif 'U' in self.data and 'T' in self.data :
            #TODO - Handle this cleanly?
            raise ValueError("Mixed RNA/DNA found")
        elif 'U' in self.data:
            d = ambiguous_rna_complement
        else:
            d = ambiguous_dna_complement
        c = dict([(x.lower(), y.lower()) for x,y in d.iteritems()])
        d.update(c)
        self.data = map(lambda c: d[c], self.data)
        self.data = array.array('c', self.data)
コード例 #31
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
    def complement(self):
        """Modify the mutable sequence to take on its complement.

        Trying to complement a protein sequence raises an exception.

        No return value"""
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins do not have complements!")
        if self.alphabet in (IUPAC.ambiguous_dna, IUPAC.unambiguous_dna):
            d = ambiguous_dna_complement
        elif self.alphabet in (IUPAC.ambiguous_rna, IUPAC.unambiguous_rna):
            d = ambiguous_rna_complement
        elif 'U' in self.data and 'T' in self.data:
            #TODO - Handle this cleanly?
            raise ValueError("Mixed RNA/DNA found")
        elif 'U' in self.data:
            d = ambiguous_rna_complement
        else:
            d = ambiguous_dna_complement
        c = dict([(x.lower(), y.lower()) for x, y in d.iteritems()])
        d.update(c)
        self.data = map(lambda c: d[c], self.data)
        self.data = array.array('c', self.data)
コード例 #32
0
def isClassIVa(base):
    """ word ends in a fricitive followed by 'te' """
    exp = explode(base)
    isClass = len(exp) > 2 and isClassIV(base) and Alphabet.isFricative(
        exp[-3])
    return isClass
コード例 #33
0
import alphabetByDiana

if __name__ == "__main__":
    print("Alphabet task has started :)")
    start = input("Enter a start string: ")  # aaa
    finish = input("Enter where to finish: ")  # aba

    print("First solution")
    printIterationOverStringsAlphabetically(start, finish)

    print("Second Solution")
    AlphabetGit.printAlphabet(start, finish)

    print("3rd Solution")
    print_char_combinations(start, finish)

    print("4th Solution")
    Alphabet.printAlphabet(start, finish)

    print("5th Solution")
    abcByDanilov.alp_start(start, finish)

    print("6th Solution")
    alphabet_Bochkareva.abc(start, finish)

    print("7th Solution")
    TaskChizh.IterateStrings(start, finish)

    print("8th Solution")
    alphabetByDiana.checkAssepted(start, finish)
コード例 #34
0
def isClassIVb(base):
    """ words that end with a vowel followed by 'te' """
    exp = explode(base)
    isClass = len(exp) > 2 and isClassIV(base) and Alphabet.isVowel(exp[-3])
    return isClass
コード例 #35
0
ファイル: Game.py プロジェクト: SahinEgilmez/AR-Word-Game
class Game:  # Logic class of all project. It uses all other classes. Main.py call it dor rendering by each frame
    faces = {}
    faceTrackers = {}
    count = 3
    alphabet = None
    currentQuestion = None
    LEVEL = 1
    time = 60  # secs per minute
    resultImage = None
    ORDER_FLAG = False

    def __init__(self):
        self.faceCascade = cv2.CascadeClassifier("./assets/haarcascade_frontalface_default.xml")
        cv2.startWindowThread()

        self.currentImage = 0  # the first image is selected
        self.currentImageID = 0
        self.rectangleColor = (0, 165, 255)
        self.frameCounter = 0
        self.currentFaceID = 0
        self.setPlayer(self.count)

    def setCapture(self, cap):  # set camera capture for initilization
        # Open the first webcame device
        self.capture = cap
        self.frameWidth = int(self.capture.get(3))  # float
        self.frameHeight = int(self.capture.get(4))  # float

    def setPlayer(self, count):  # set player number and get questions according to this.
        self.count = count
        self.alphabet = Alphabet(count)

        self.currentQuestion = self.alphabet.getQuestion()
        for i in range(0, count):
            self.faces[i] = Face(i, None)
            self.faceTrackers[i] = None
            if(self.faces[i].letter is None):
                self.faces[i].letter = self.currentQuestion.answer[i]

    def render(self):  # rendering function of game. Main.py calls it each frame
        # Retrieve the latest image from the webcam
        rc, baseImage = self.capture.read()
        baseImage = cv2.flip(baseImage, 1)  # mirror effect

        # Copy base image
        self.resultImage = baseImage.copy()

        # Increase the framecounter
        self.frameCounter += 1

        # Update all the trackers and remove the ones for which the update
        # indicated the quality was not good enough
        fidsToDelete = []
        for i in range(self.count):
            if(self.faces[i].tracker is not None):
                trackingQuality = self.faces[i].update(baseImage)
                # If the tracking quality is good enough, we must delete
                # this tracker
                if trackingQuality < 7:
                    self.faces[i].tracker = None

        # Every 10 frames, we will have to determine which faces
        # are present in the frame
        if (self.frameCounter % 10) == 0:
            # For the face detection, we need to make use of a gray
            # colored image so we will convert the baseImage to a
            # gray-based image
            gray = cv2.cvtColor(baseImage, cv2.COLOR_BGR2GRAY)
            # Now use the haar cascade detector to find all faces
            # in the image
            localFaces = self.faceCascade.detectMultiScale(gray, 1.3, 5)

            # Loop over all faces and check if the area for this
            # face is the largest so far
            # We need to convert it to int here because of the
            # requirement of the dlib tracker. If we omit the cast to
            # int here, you will get cast errors since the detector
            # returns numpy.int32 and the tracker requires an int
            for (_x, _y, _w, _h) in localFaces:
                x = int(_x)
                y = int(_y)
                w = int(_w)
                h = int(_h)

                # calculate the centerpoint
                x_bar = x + 0.5 * w
                y_bar = y + 0.5 * h

                # Variable holding information which faceid we
                # matched with
                matchedFid = None

                # Now loop over all the trackers and check if the
                # centerpoint of the face is within the box of a
                # tracker
                for i in range(self.count):
                    if(self.faces[i].tracker is not None):
                        self.faces[i].update(baseImage)
                        pos = self.faces[i].tracker.get_position()

                        t_x = int(pos.left())
                        t_y = int(pos.top())
                        t_w = int(pos.width())
                        t_h = int(pos.height())

                        # calculate the centerpoint
                        t_x_bar = t_x + 0.5 * t_w
                        t_y_bar = t_y + 0.5 * t_h

                        # check if the centerpoint of the face is within the
                        # rectangleof a tracker region. Also, the centerpoint
                        # of the tracker region must be within the region
                        # detected as a face. If both of these conditions hold
                        # we have a match
                        if ((t_x <= x_bar <= (t_x + t_w)) and
                            (t_y <= y_bar <= (t_y + t_h)) and
                            (x <= t_x_bar <= (x + w)) and
                                (y <= t_y_bar <= (y + h))):
                            matchedFid = True

                # If no matched fid, then we have to create a new tracker
                if matchedFid is None:
                    # Create and store the tracker
                    tracker = dlib.correlation_tracker()
                    tracker.start_track(baseImage, dlib.rectangle(x, y, x+w, y+h))
                    pos = tracker.get_position()

                    t_x = int(pos.left())
                    t_y = int(pos.top())
                    t_w = int(pos.width())
                    t_h = int(pos.height())

                    for i in range(self.count):
                        if(self.faces[i].tracker is None):
                            if(self.faces[i].encoding is None):
                                if(self.faces[i].save(baseImage[t_y:t_y+t_h, t_x:t_x+t_w]) is True):
                                    self.faces[i].tracker = tracker
                                    self.faces[i].update(baseImage)
                                    break
                            else:
                                crop = baseImage[t_y:t_y + t_h, t_x:t_x+t_w]
                                if(self.faces[i].checkFace(crop) is True):
                                    self.faces[i].tracker = tracker
                                    self.faces[i].update(baseImage)
                                    break
                    # Increase the currentFaceID counter
                    self.currentFaceID += 1

        for i in range(self.count):
            if(self.faces[i].tracker is not None):
                t_x = int(self.faces[i].x)
                t_y = int(self.faces[i].y)
                t_w = int(self.faces[i].w)
                t_h = int(self.faces[i].h)

                replaceImg = read_transparent_png(self.faces[i].letter)
                rows, cols, ch = replaceImg.shape
                # this points are necesary for the transformation
                pts1 = np.float32(
                    [[0, 0], [cols, 0], [cols, rows], [0, rows]])
                self.currentImage += 1
                # pts2 is used for defining the perspective transform
                pts2 = np.float32([[t_x, (DISTANCE_OF_LETTER*t_y)], [(t_x+t_w), (DISTANCE_OF_LETTER*t_y)],
                                   [(t_x+t_w), ((DISTANCE_OF_LETTER*t_y)+t_h)], [t_x, ((DISTANCE_OF_LETTER*t_y)+t_h)]])
                # compute the transform matrix
                M = cv2.getPerspectiveTransform(pts1, pts2)
                rows, cols, ch = self.resultImage.shape
                # make the perspective change in a image of the size of the camera input
                dst = cv2.warpPerspective(replaceImg, M, (cols, rows))
                # A mask is created for adding the two images
                # maskThreshold is a variable because that allows to substract the black background from different images
                ret, mask = cv2.threshold(cv2.cvtColor(
                    dst, cv2.COLOR_BGR2GRAY), MASK_TRESHOLD, 1, cv2.THRESH_BINARY_INV)
                # Erode and dilate are used to delete the noise
                mask = cv2.erode(mask, (3, 3))
                mask = cv2.dilate(mask, (3, 3))
                # The two images are added using the mask
                for c in range(0, 3):
                    self.resultImage[:, :, c] = dst[:, :, c] * \
                        (1-mask[:, :]) + self.resultImage[:, :, c]*mask[:, :]

                cv2.rectangle(self.resultImage, (t_x, t_y), (t_x + t_w, t_y + t_h), self.rectangleColor, 2)

        # draw question
        self.resultImage = self.drawQuestion(self.currentQuestion.question, self.frameHeight, self.frameWidth)

        if(self.isOrderTrue() is True):
            self.ORDER_FLAG = True
            print("ORDER IS TRUE")
            self.nextQuestion()
        return self.resultImage

    def dispose(self):  # dispose all datas when game closed or finished game
        # Destroy any OpenCV windows and exit the application
        self.capture.release()
        cv2.CAP_MSMF = 0
        cv2.destroyAllWindows()

    def isOrderTrue(self):  # checker for right order
        order = True
        lst = []
        for i in range(self.count):
            lst.append(self.faces[i].letter)
        lst.sort(key=lambda x: x.id, reverse=False)

        for i in range(self.count-1):
            x1 = lst[i].x
            x2 = lst[i+1].x
            if(x1 >= x2):  # if before x is bigger return false, otherwise true
                order = False
                break
        return order

    def nextQuestion(self):  # get next wuestion from Alphabet class
        self.LEVEL += 1
        self.currentQuestion = self.alphabet.getQuestion()
        for i in range(0, self.count):
            self.faces[i] = Face(-1, None)
            self.faceTrackers[i] = None
            if(self.faces[i].letter is None):
                self.faces[i].letter = self.currentQuestion.answer[i]

    def drawQuestion(self, word, fHeight, fWidth):  # draw question using OpenCV
        fontpath = "./assets/TTWPGOTT.ttf"
        (r, g, b, a) = (125, 222, 205, 1)
        line = word
        ft = ImageFont.truetype(fontpath, 20)
        img_pil = Image.fromarray(self.resultImage)
        draw = ImageDraw.Draw(img_pil)
        if(len(line) > 60):
            draw.rectangle(
                [(40, fHeight - 45), (fWidth-40, fHeight-5)], (61, 0, 59, 1))
            line1 = line[0:60]
            line2 = line[60:len(line)]
            draw.text((50, fHeight - 45),  line1,
                      font=ft, fill=(r, g, b, a))
            draw.text((50, fHeight - 25),  line2,
                      font=ft, fill=(r, g, b, a))
        else:
            draw.rectangle(
                [(40, fHeight - 45), (fWidth-40, fHeight-5)], (61, 0, 59, 1))
            draw.text((50, fHeight - 30),  line,
                      font=ft, fill=(r, g, b, a))

        # level
        draw.text((fWidth - 50, 5), str("LEVEL"), font=ft, fill=(61, 0, 59, 1))
        draw.ellipse([(fWidth - 50, 25), (fWidth-10, 65)], (61, 0, 59, 1))
        draw.text((fWidth - 40, 35), str("{:02d}".format(self.LEVEL)), font=ft, fill=(r, g, b, a))

        # time
        draw.text((15, 5), str("SÜRE"), font=ft, fill=(61, 0, 59, 1))
        draw.ellipse([(10, 25), (50, 65)], (61, 0, 59, 1))
        draw.text((20, 35), str("{:02d}".format(self.time)), font=ft, fill=(r, g, b, a))

        return np.array(img_pil)
コード例 #36
0
import Alphabet

Alphabet.GenerateVigenereTable()
コード例 #37
0
ファイル: Seq.py プロジェクト: nuin/biopython
    def translate(self, table="Standard", stop_symbol="*", to_stop=False):
        """Turns a nucleotide sequence into a protein sequence. New Seq object.

        Trying to back-transcribe a protein sequence raises an exception.
        This method will translate DNA or RNA sequences.

        Trying to translate a protein sequence raises an exception.

        table - Which codon table to use?  This can be either a name
                (string) or an NCBI identifier (integer).  This defaults
                to the "Standard" table.
        stop_symbol - Single character string, what to use for terminators.
                This defaults to the asterisk, "*".
        to_stop - Boolean, defaults to False meaning do a full translation
                continuing on past any stop codons (translated as the
                specified stop_symbol).  If True, translation is terminated
                at the first in frame stop codon (and the stop_symbol is
                not appended to the returned protein sequence).

        e.g. Using the standard table,
        
        >>> coding_dna = Seq("GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG")
        >>> coding_dna.translate()
        Seq('VAIVMGR*KGAR*', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> coding_dna.translate(stop_symbol="@")
        Seq('VAIVMGR@KGAR@', HasStopCodon(ExtendedIUPACProtein(), '@'))
        >>> coding_dna.translate(to_stop=True)
        Seq('VAIVMGR', ExtendedIUPACProtein())
        
        Now using NCBI table 2, where TGA is not a stop codon:
        
        >>> coding_dna.translate(table=2)
        Seq('VAIVMGRWKGAR*', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> coding_dna.translate(table=2, to_stop=True)
        Seq('VAIVMGRWKGAR', ExtendedIUPACProtein())

        If the sequence has no in-frame stop codon, then the to_stop argument
        has no effect:

        >>> coding_dna2 = Seq("TTGGCCATTGTAATGGGCCGC")
        >>> coding_dna2.translate()
        Seq('LAIVMGR', ExtendedIUPACProtein())
        >>> coding_dna2.translate(to_stop=True)
        Seq('LAIVMGR', ExtendedIUPACProtein())

        NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid
        or a stop codon.  These are translated as "X".  Any invalid codon
        (e.g. "TA?" or "T-A") will throw a TranslationError.

        NOTE - Does NOT support gapped sequences.

        NOTE - This does NOT behave like the python string's translate
        method.  For that use str(my_seq).translate(...) instead.
        """
        try:
            table_id = int(table)
        except ValueError:
            table_id = None
        if isinstance(table, str) and len(table)==256 :
            raise ValueError("The Seq object translate method DOES NOT take " \
                             + "a 256 character string mapping table like " \
                             + "the python string object's translate method. " \
                             + "Use str(my_seq).translate(...) instead.")
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet) :
            raise ValueError("Proteins cannot be translated!")
        if self.alphabet==IUPAC.unambiguous_dna:
            if table_id is None:
                codon_table = CodonTable.unambiguous_dna_by_name[table]
            else:
                codon_table = CodonTable.unambiguous_dna_by_id[table_id]
        elif self.alphabet==IUPAC.ambiguous_dna:
            if table_id is None:
                codon_table = CodonTable.ambiguous_dna_by_name[table]
            else:
                codon_table = CodonTable.ambiguous_dna_by_id[table_id]
        elif self.alphabet==IUPAC.unambiguous_rna:
            if table_id is None:
                codon_table = CodonTable.unambiguous_rna_by_name[table]
            else:
                codon_table = CodonTable.unambiguous_rna_by_id[table_id]
        elif self.alphabet==IUPAC.ambiguous_rna:
            if table_id is None:
                codon_table = CodonTable.ambiguous_rna_by_name[table]
            else:
                codon_table = CodonTable.ambiguous_rna_by_id[table_id]
        else:
            if table_id is None:
                codon_table = CodonTable.ambiguous_generic_by_name[table]
            else:
                codon_table = CodonTable.ambiguous_generic_by_id[table_id]
        protein = _translate_str(str(self), codon_table, stop_symbol, to_stop)
        if stop_symbol in protein :
            alphabet = Alphabet.HasStopCodon(codon_table.protein_alphabet,
                                             stop_symbol = stop_symbol)
        else :
            alphabet = codon_table.protein_alphabet
        return Seq(protein, alphabet)
コード例 #38
0
def isClassII(base):
    """ word ends in 2 prime vowels """
    exp = explode(base)
    isClass = len(exp) > 1 and Alphabet.isPrimeVowel(
        exp[-1]) and Alphabet.isPrimeVowel(exp[-2])
    return isClass
コード例 #39
0
ファイル: Seq.py プロジェクト: manucorreia/biopython
    def translate(self, table="Standard", stop_symbol="*", to_stop=False):
        """Turns a nucleotide sequence into a protein sequence. New Seq object.

        Trying to back-transcribe a protein sequence raises an exception.
        This method will translate DNA or RNA sequences.

        Trying to translate a protein sequence raises an exception.

        table - Which codon table to use?  This can be either a name
                (string) or an NCBI identifier (integer).  This defaults
                to the "Standard" table.
        stop_symbol - Single character string, what to use for terminators.
                This defaults to the asterisk, "*".
        to_stop - Boolean, defaults to False meaning do a full translation
                continuing on past any stop codons (translated as the
                specified stop_symbol).  If True, translation is terminated
                at the first in frame stop codon (and the stop_symbol is
                not appended to the returned protein sequence).

        e.g. Using the standard table,
        
        >>> coding_dna = Seq("GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG")
        >>> coding_dna.translate()
        Seq('VAIVMGR*KGAR*', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> coding_dna.translate(stop_symbol="@")
        Seq('VAIVMGR@KGAR@', HasStopCodon(ExtendedIUPACProtein(), '@'))
        >>> coding_dna.translate(to_stop=True)
        Seq('VAIVMGR', ExtendedIUPACProtein())
        
        Now using NCBI table 2, where TGA is not a stop codon:
        
        >>> coding_dna.translate(table=2)
        Seq('VAIVMGRWKGAR*', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> coding_dna.translate(table=2, to_stop=True)
        Seq('VAIVMGRWKGAR', ExtendedIUPACProtein())

        If the sequence has no in-frame stop codon, then the to_stop argument
        has no effect:

        >>> coding_dna2 = Seq("TTGGCCATTGTAATGGGCCGC")
        >>> coding_dna2.translate()
        Seq('LAIVMGR', ExtendedIUPACProtein())
        >>> coding_dna2.translate(to_stop=True)
        Seq('LAIVMGR', ExtendedIUPACProtein())

        NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid
        or a stop codon.  These are translated as "X".  Any invalid codon
        (e.g. "TA?" or "T-A") will throw a TranslationError.

        NOTE - Does NOT support gapped sequences.

        NOTE - This does NOT behave like the python string's translate
        method.  For that use str(my_seq).translate(...) instead.
        """
        try:
            table_id = int(table)
        except ValueError:
            table_id = None
        if isinstance(table, str) and len(table) == 256:
            raise ValueError("The Seq object translate method DOES NOT take " \
                             + "a 256 character string mapping table like " \
                             + "the python string object's translate method. " \
                             + "Use str(my_seq).translate(...) instead.")
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins cannot be translated!")
        if self.alphabet == IUPAC.unambiguous_dna:
            if table_id is None:
                codon_table = CodonTable.unambiguous_dna_by_name[table]
            else:
                codon_table = CodonTable.unambiguous_dna_by_id[table_id]
        elif self.alphabet == IUPAC.ambiguous_dna:
            if table_id is None:
                codon_table = CodonTable.ambiguous_dna_by_name[table]
            else:
                codon_table = CodonTable.ambiguous_dna_by_id[table_id]
        elif self.alphabet == IUPAC.unambiguous_rna:
            if table_id is None:
                codon_table = CodonTable.unambiguous_rna_by_name[table]
            else:
                codon_table = CodonTable.unambiguous_rna_by_id[table_id]
        elif self.alphabet == IUPAC.ambiguous_rna:
            if table_id is None:
                codon_table = CodonTable.ambiguous_rna_by_name[table]
            else:
                codon_table = CodonTable.ambiguous_rna_by_id[table_id]
        else:
            if table_id is None:
                codon_table = CodonTable.ambiguous_generic_by_name[table]
            else:
                codon_table = CodonTable.ambiguous_generic_by_id[table_id]
        protein = _translate_str(str(self), codon_table, stop_symbol, to_stop)
        if stop_symbol in protein:
            alphabet = Alphabet.HasStopCodon(codon_table.protein_alphabet,
                                             stop_symbol=stop_symbol)
        else:
            alphabet = codon_table.protein_alphabet
        return Seq(protein, alphabet)
コード例 #40
0
ファイル: Base.py プロジェクト: WileESpaghetti/learn-yupik
def isClassII(base):
	""" word ends in 2 prime vowels """
	exp = explode(base)
	isClass = len(exp) > 1 and Alphabet.isPrimeVowel(exp[-1]) and Alphabet.isPrimeVowel(exp[-2])
	return isClass
コード例 #41
0
ファイル: Base.py プロジェクト: WileESpaghetti/learn-yupik
def isClassVI(base):
	""" all words ending in a consonant and that are not Class V """
	exp = explode(base)
	isClass = len(exp) > 1 and Alphabet.isConsonant(exp[-1]) and not isClassV(base)
	return isClass
コード例 #42
0
ファイル: Base.py プロジェクト: WileESpaghetti/learn-yupik
def isClassIVa(base):
	""" word ends in a fricitive followed by 'te' """
	exp = explode(base)
	isClass = len(exp) > 2 and isClassIV(base) and Alphabet.isFricative(exp[-3])
	return isClass
コード例 #43
0
ファイル: Base.py プロジェクト: WileESpaghetti/learn-yupik
def isClassIVb(base):
	""" words that end with a vowel followed by 'te' """
	exp = explode(base)
	isClass = len(exp) > 2 and isClassIV(base) and Alphabet.isVowel(exp[-3])
	return isClass
コード例 #44
0
 def test_reverse(self):
     rever = Alphabet.reverse('Hello Everyone')
     self.assertEqual(rever, 'The reverse of String: enoyrevE olleH')
コード例 #45
0
 def test_word_length(self):
     self.assertEqual(Alphabet.word_length("Welcome to TCS"),
                      'The number of characters in "Welcome to TCS" is 12')
     self.assertEqual(Alphabet.word_length(""),
                      'The number of characters in "" is 0')
コード例 #46
0
    def test_palindrome_or_not(self):
        palinsent1 = Alphabet.palindrome_or_not('Hello Everyone')
        self.assertEqual(palinsent1, "Its Not a Palindrome")

        palinsent2 = Alphabet.palindrome_or_not('Race car')
        self.assertEqual(palinsent2, "Its a Palindrome")