简体   繁体   English

如何使用字符映射表替换字符串中的字符?

[英]How do I replace characters in a string using a character map?

Code purpose: 代码用途:

I provide a string and match it with dictionary keys; 我提供了一个字符串,并将其与字典键匹配; if the key and string match I print the dictionary values. 如果键和字符串匹配,我将打印字典值。

Here's the code: 这是代码:

def to_rna(dna_input):
    dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
    rna = []
    for key in dna_rna.iterkeys():
        if key in dna_input:
            rna.append(dna_rna[key])
    print "".join(rna)

to_rna("ACGTGGTCTTAA") #the string input

Problem: 问题:

The result should be ' UGCACCAGAAUU ' but all I get is ' UGAC '. 结果应该是“ UGCACCAGAAUU ”,但我得到的只是“ UGAC ”。 The problem appears to be that I have duplicate characters in the string and the loop is ignoring this. 问题似乎是我在字符串中有重复的字符,并且循环忽略了这一点。 How do I loop through the dictionary so that it returns the dictionary value as many times as the dict key is found? 如何遍历字典,以便它与找到dict键一样多次返回字典值?

You could use translate() . 您可以使用translate() Edit: I added the regex to return - for bad entries (seemed like a good idea @jh44tx had): 编辑:我添加了正则表达式返回-错误的条目(似乎是个好主意@ jh44tx):

import string
import re
rna_trans = string.maketrans("ACGTU","UGCA-")
rna_trans = re.sub("[^UGCA]","-",rna_trans)
print "ACGTGGTCTTAA".translate(rna_trans)

Since the mappings are 1:1 you can also create a reverse translate: 由于映射是1:1,因此您还可以创建反向翻译:

rev_rna_trans = string.maketrans("UGCAT","ACGT-")
rev_rna_trans = re.sub("[^ACGT]","-",rna_trans)

If you want to output a character for every character in dna_input you need to iterate over character in dna_input . 如果要为dna_input每个字符输出一个字符,则需要遍历dna_input字符。 Note that the get() function provides a default for characters that aren't in your dictionary. 请注意, get()函数为不在词典中的字符提供默认设置。 I am replacing with nothing, if desired you could put an n here, or an X. 我什么都没替换,如果需要,您可以在此处输入n或X。

rna.append(dna_rna.get(char, 'n'))

Your code was only iterating over the 4 entries in the dna_rna dictionary. 您的代码仅迭代dna_rna词典中的4个条目。

def to_rna(dna_input):
    dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
    rna = []
    for char in dna_input:
        rna.append(dna_rna.get(char, ''))
    print "".join(rna)

to_rna("ACGTGGTCTTAA") #the string input

However, this isn't the most efficient way to translate a string. 但是,这不是翻译字符串的最有效方法。

Since you know that each letter of the input will be translated to an output string, you're better off making a loop over each letter: 由于您知道输入的每个字母都会转换为输出字符串,因此最好对每个字母进行循环:

def to_rna(dna_input):
    dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
    rna = []
    for x in dna_input:
        rna.append(dna_rna[x])
    return ''.join(rna)

or you could write it with list comprehensions 或者你可以用列表理解来写

def to_rna(dna_input):
    dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
    return ''.join([dna_rna[x] for x in dna_input])

Just in case you think you'll get junk letters sometimes, you can do this: 万一您认为有时会收到垃圾信件,可以这样做:

def to_rna(dna_input):
    dna_rna={'A':'U','C':'G','G':'C','T':'A'}
    rna=[]
    for char in dna_input:
        if char in dna_rna.keys():
            rna.append(dna_rna[char])
        else:
            rna.append('-')
    print "".join(rna)

to_rna("ACGTGGTCTTAAX")

and the result is: UGCACCAGAAUU- 其结果是: UGCACCAGAAUU-

You can do this as a list comprehension. 您可以将其作为列表理解。 Because this becomes a one-liner it pretty much makes the function superfluous: 因为这变成了单行代码,所以几乎使该函数变得多余:

def to_rna(dna_input):
    dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
    return "".join([dna_rna.get(x, '') for x in dna_input])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何用范围替换字符串中的字符? - how do i replace a character in a string by range? 如何在Python中替换字符串中的字符? - How do I replace characters in a string in Python? 如何正确替换字符串中的字符? - How do I correctly replace characters in a string? 如何用 Python 中的另一个字符替换字符串中的一个字符? - How do I replace a character in a string with another character in Python? 如何检查字符串是否包含字符和空格(空字符)? - How do I check if a string includes characters and space (empty character)? 如何将字符与Python中某个字符串中的所有字符进行比较? - How do I compare a character to all the characters in some string in Python? 如何在Python 3.5中为使用随机替换字符串中字符的函数编写doctest? - How do I write a doctest in python 3.5 for a function using random to replace characters in a string? 如何在Python中替换字符串中的字符,但不使用字符串方法? - How can I replace characters in a string in Python, but not using string methods? 如何替换字符串中的多个字符 Python - How do I replace more than one character in a string Python 在 Pandas Python 中,如何替换字符串列中的字符? - In Pandas Python how do i replace Characters in String column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM