3

我有一个包含字母和标点符号的字符串。我试图只用其他字母替换这个字符串中的字母。我开发的函数只适用于包含字母的字符串。如果包含数字,则会产生逻辑错误,如果包含标点符号,则会产生运行时错误。无论如何,我可以让我的功能忽略标点符号并保持原样,同时只对字母进行操作?

#Create a string variable, ABjumbler generates an alphabet shifted by x units to the right
#ABshifter converts a string using one type to another

textObject = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
smalltext = 'abcde'

alphabet = list(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'])

def ABjumbler(alphabet, x):
    freshset = []
    i=0
    j=0
    while i<(len(alphabet)-x):
        freshset.extend(alphabet[i+x])
        i+=1
    while j<x:
    freshset.extend(alphabet[j]) #extend [0]
    j+=1 #change j = to 1, extends by [1], then by [2], and then terminates when it reaches x
    alphabet = freshset
    return alphabet

newAlphabet = ABjumbler(alphabet, 2)

def ABshifter(text, shiftedalphabet):
    freshset = []
    for letters in text:
        position = text.index(letters)
        freshset.extend(shiftedalphabet[position])
    final = ''.join(freshset)
    return final

print ABshifter(smalltext, newAlphabet)
4

4 回答 4

2

一方面,有一些更快/更简单的方法来完成你想要的转变。

但要回答您的问题,您可以简单地添加:

if not letter.isalpha():
    continue

str.isalpha()True如果字符串仅由字母组成,则返回。

于 2013-08-10T15:22:41.700 回答
1

Try this one:

textObject = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
smalltext = 'abcde'

alphabet = list(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'])

def ABjumbler(alphabet, x):
    #for x greater then alphabet length
    if x>=len(alphabet):
        x = x % len(alphabet)
    #return a dictionary like 'a':'c', 'b':'d' etc
    return dict(zip(alphabet, alphabet[x:] + alphabet[:x]))

def ABshifter(letter, alph):
    if letter.isalpha():
        return alph[letter]
    return letter

print "".join(map(lambda x: ABshifter(x, ABjumbler(alphabet,2)), smalltext))
于 2013-08-10T15:53:19.317 回答
1

1)

x = ['a', 'b', 'c']
print x

y = list(['a', 'b', 'c'])
print y

--output:--
['a', 'b', 'c']
['a', 'b', 'c']

Any difference? Then don't call list() when it's unnecessary.

2)

x.append('d')
y.extend(['d'])

print x
print y

['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']

Any difference? Then don't create a list with 'd' inside if it's unnecessary.

Your whole ABjumbler() function can be reduced to one line:

cypher = alphabet[x:] + alphabet[:x]

Examine this code:

import string

x = 23
letters = string.ascii_lowercase

print letters[x:]    #xyz
print letters[:x]    #abcdefghijklmnopqrstuvw
print "-" * 10

cypher = letters[x:] + letters[:x]
print cypher         #xyzabcdefghijklmnopqrstuvw

table = string.maketrans(letters, cypher)

The maketrans() function constructs a translation table like this:

letters:  abcdefghijklmnopqrstuvwxyz
 cypher:  xyzabcdefghijklmnopqrstuvw

If the letters on top are found in a string, they get translated to the letters directly beneath them:

x = "aaa"
print x.translate(table)   #xxx

x = 'abc'
print x.translate(table)   #xyz

x = 'a1bc!'
print x.translate(table)   #x1yz!


x = '123a-b-c!!!!a.b.c456'
print x
print x.translate(table)  

--output:--
123a-b-c!!!!a.b.c456
123x-y-z!!!!x.y.z456

If x might be larger than the length of your alphabet, then write:

x = x % len(letters)

before constructing the cypher.

import string

def encode_it(str_, letters, offset):
    offset = offset % len(letters)
    cypher = letters[offset:] + letters[:offset]
    table = string.maketrans(letters, cypher)
    return str_.translate(table)
于 2013-08-10T16:09:38.193 回答
0

您可以使用该string.ascii_letters常量来检查当前字符是否为字母。这是一个将字符串中的所有字母替换为 'x' 的片段(我知道这不是想要做的,但它可能会让您入门):


    import string

    s = "g fmnc, wma: bgblr?"
    sList = list(s)

    for i in range(0, len(sList)):
        if sList[i] in string.ascii_letters
            j[i] = 'x'
        s = ''.join(j)

    print(s) #'x xxxx, xxx: xxxxx?'
于 2013-08-10T15:28:37.067 回答