【问题标题】:Joining consonants and vowels in python在python中加入辅音和元音
【发布时间】:2015-12-17 08:13:42
【问题描述】:

我已经在脚本中定义了元音。接下来我希望能够将辅音和元音连接在一起,

例如:

如果辅音跟在元音后面,我想取出单词的那一部分并将其组合在一个列表中。

如果我有“房子”这个词,我希望能够在类似的列表中输出

['h', 'ous', 'e]  

我应该先把这个词分开,这样就可以了

['h', 'o', 'u', 's', 'e'] 

然后担心将它们加在一起,或者最好的方法是什么?

我正在考虑使用 while 或 for 循环。

【问题讨论】:

  • 你能告诉我们你现在拥有的代码吗?
  • 好的,然后使用您觉得舒服的循环并进行一些编码。如果您在代码中遇到问题,请提出问题,当然是代码部分。
  • 您愿意使用正则表达式解决方案吗?
  • 你认为 (U+0065 U+0301) 是元音吗?在您的应用程序中应该将其视为一两个字符吗?发音算不算? Is there a vowel in nth?

标签: python list loops grouping


【解决方案1】:

更多示例会有所帮助,但以下方法似乎适用于您当前的 house 示例:

print [g for g in re.split(r'([aeiou]+?[^aeiou]+?)', 'house', flags=re.I) if g]

这显示:

['h', 'ous', 'e']

【讨论】:

    【解决方案2】:

    我认为这个函数可以满足你的需要:

    vowels = ['a', 'e', 'i', 'o', 'u']
    consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
    
    def group_vowels(string):
        output = []
        substring = ''
        # Loop through each character in the string
        for i, c in enumerate(string, start=1):
            # If it's a consonant, add it to the current substring
            # and then add the substring to the output list
            if c in consonants:
                substring = substring + c
                output.append(substring)
                substring = ''
            # If it's a vowel, add it to the current substring
            if c in vowels:
                substring = substring + c
                # If the word ends with vowels, add them to the output list
                if i == len(string): output.append(substring)
        return output
    
    print group_vowels('house') # ['h', 'ous', 'e']
    print group_vowels('ouagadougou') # ['ouag', 'ad', 'oug', 'ou']
    

    正如 J.F. Sebastian 评论的那样,您可能想要扩展 vowelsconsonants 列表。

    【讨论】:

    • 您在第二个示例中缺少一些输出,最后应该是 ou
    • 您还可以为 0(1) 次查找设置元音和辅音
    猜你喜欢
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2018-01-14
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    相关资源
    最近更新 更多