【问题标题】:Python Letter ChangerPython 字母转换器
【发布时间】:2014-02-17 16:02:21
【问题描述】:

我正在开发一个程序,该程序从任何变量(var、var2)中获取字符串并将元音更改为任何随机元音。我试图这样做,但我的代码不起作用,它总是打印没有元音。

import random
alph = list('abcdefgkijklmnopqrstuvwxyz')
vow = list('aeiou')
Alphabet = ['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']
Vowels = ['a', 'e', 'i', 'o', 'u']
Consences = ['b','c','d','f','g','h','j','k','l','m','n','p', 'q' ,'r' ,'s', 't', 'v', 'w', 'x' ,'y','z']

ranVowel= random.choice(Vowels)
print(ranVowel)


var2 = ['i']
var = list("cat")

def ifVowel(x):
    if (Vowels in x):
        print 'there is a vowel'
        var[var.index(vow)] = ranVowel
    elif (Vowels not in x):
        print 'there is no vowel'
    else: print 'no vowels'

ifVowel(var2)

【问题讨论】:

  • "but my code doesn't work":虽然在这种情况下问题很容易发现,但这还不够具体,不能成为一个好问题的一部分。你期望你的代码做什么?你的代码做了什么?您可以将意外行为缩小到代码的哪一部分?此时所涉及的变量的值和类型是什么?等等。

标签: python list random function


【解决方案1】:

你的测试

if (Vowels in x):

正在检查整个列表Vowels = ['a', 'e', 'i', 'o', 'u'] 是否是in x,并且可能永远不会是True。相反,你想要:

if any(vowel in x for vowel in Vowels):

单独测试每一个。还有

var[var.index(vow)] = ranVowel

只会替换第一个元音。您需要遍历字符串以替换所有元音,例如:

replaced = "".join(c if c not in Vowels else random.choice(Vowels) for c in x)

请注意,所有这些都只适用于小写,因此您可能希望使用x.lower() 或明确处理大写。

最后,不是元音的东西都是辅音。

【讨论】:

    【解决方案2】:

    可以将re 与函数替换一起使用...,例如:

    >>> import re, random
    >>> vowels = 'aeiou'
    >>> text = 'this is something with vowels in'
    >>> re.sub('[aeiou]', lambda L: random.choice(vowels), text, flags=re.I)
    'thos is semithung wath vawuls in'
    

    【讨论】:

    • 我希望这是最有效和最高效的解决方案。 +1
    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多