【问题标题】:Evaluate consonant/vowel composition of word string in Python在 Python 中评估单词字符串的辅音/元音组成
【发布时间】:2020-08-19 07:12:39
【问题描述】:

我正在尝试将 Python 字符串从其原始形式转换为其元音/辅音组合。

例如 - 'Dog' 变成 'cvc' 而 'Bike' 变成 'cvcv'

在 R 中,我能够使用以下方法:

   con_vowel <- gsub("[aeiouAEIOU]","V",df$col_name)
   con_vowel <- gsub("[^V]","C",con_vowel)
   df[["composition"]] <- con_vowel

这将评估字符是否为元音,如果为真,则分配字符“V”,然后评估该字符串并将不是“V”的任何内容替换为“C”,然后将结果放入名为“数据框中的组合'。

在 Python 中,我在尝试中编写了一些代码来复制功能,但它没有返回所需的结果。请看下文。

word = 'yoyo'


for i in word.lower():
    if i in "aeiou":
       word = i.replace(i ,'v')
    else: word = i.replace(i ,'c')
print(word)

这里的理论是每个字符都会被评估,如果它不是元音,那么通过演绎它必须是辅音。 但是我得到的结果是:

v

我明白为什么会这样,但我不清楚如何达到我想要的结果。

请注意,我还需要将生成的代码应用于数据框列并根据这些结果创建一个新列。

如果你能解释你的答案的工作原理,那将对我有很大帮助。

提前致谢。

【问题讨论】:

  • 尝试创建一个新字符串而不是更改原始字符串。
  • 作为一名语言学家,看到这个辅音和元音的定义让我心痛。 :^)
  • 对于句子或任何带有非标准字符的单词也有问题:"I'm an X-ray!' 按照这种逻辑将太多东西归类为“辅音”。
  • 绝对!那么数字和特殊字符呢?许多答案只是将它们视为辅音......
  • 完全理解意外字符的观察结果,但不适用,因为字符串只会包含拉丁字母字符。

标签: python string pandas function jupyter-notebook


【解决方案1】:

在 Python 中,字符串是不可变的。
为什么?

有几个优点。

一个是性能:知道字符串是不可变的意味着我们可以 在创建时为其分配空间,以及存储要求 是固定不变的。这也是原因之一 元组和列表的区别。

另一个优点是 Python 中的字符串被视为 “基本”作为数字。没有活动量会改变值 8 对于其他任何东西,在 Python 中,任何活动都不会改变 字符串“八”到其他任何东西。

为了减少混淆和潜在错误,最好创建一个新字符串而不是更改原始字符串。 我还添加了 is_alpha() 以便能够了解我们是在处理字母还是数字/符号并采取相应措施。

这是我的代码:

word = 'yoyo'

def vocals_consonants_transformation(word):
    modified_word = ""
    for i in range(0, len(word)):
        if word[i].isalpha():
            if word[i] in "aeiou":
                modified_word += 'v'
            else:
                modified_word += 'c'
        else:
            modified_word += word[i]
    return modified_word


print(vocals_consonants_transformation(word))

输出
简历

来源:
https://docs.python.org/3/faq/design.html#why-are-python-strings-immutable

【讨论】:

    【解决方案2】:

    试试这个:

    word = 'yoyo'
    word = list(word)
    
    for i in range(len(word)):
        if word[i] in 'aeiou':
            word[i] = 'v'
        else:
            word[i] = 'c'
    
    print(''.join(word))
    

    【讨论】:

      【解决方案3】:

      试试这样:

      word = 'yoyo'
      
      for i in word.lower():
          if i in "aeiou":
             word=word.replace(i ,'v')
          else:
              word=word.replace(i ,'c')
      print(word)
      

      【讨论】:

        【解决方案4】:
        vowels = set("aeiou")
        word = "Dog"
        
        new_word = ""
        for char in word.lower():
            new_word += "v" if char in vowels else "c"
        
        print(new_word)
        

        请注意 这将set 用于元音以加快成员资格测试。除此之外,我们遍历word 的低版本并通过三元组将所需的字符(vc)添加到新形成的字符串中。

        【讨论】:

          【解决方案5】:

          您可能已经意识到这一点,但在您的解决方案中,for 循环确定每个字母是否为元音,但不保存结果。这就是为什么它只给你最后一次迭代的结果(v,因为 'o' 是元音)。

          您可以尝试创建一个新的空字符串,然后添加到其中:

          word='yoyo'
          new_word=''
          
          for i in word.lower():
              if i in "aeiou":
                  new_word+='v'
              else:
                  new_word+='c'
          
          print(new_word)
          

          【讨论】:

            【解决方案6】:

            使用 string.replace 和一些正则表达式来避免循环

            df = pd.DataFrame(['Cat', 'DOG', 'bike'], columns=['words'])
            # use string.replace
            df['new_word'] = df['words'].str.lower().str.replace(r"[^aeiuo]", 'c').str.replace(r"[aeiou]", 'v')
            print(df)
            
              words new_word
            0   Cat      cvc
            1   DOG      cvc
            2  bike     cvcv
            

            【讨论】:

              【解决方案7】:

              您可以将replaceregex=True 一起使用:

              words = pd.Series(['This', 'is', 'an', 'Example'])
              words.str.lower().replace({"[^aeiou]":'c', '[aeiou]':'v'}, regex=True)
              

              输出:

              0       ccvc
              1         vc
              2         vc
              3    vcvcccv
              dtype: object
              

              【讨论】:

                【解决方案8】:

                有一个方法;这是translate。传递翻译表中找不到的值(如' ')既有效又默认。

                如果需要,您可以使用 string 库来获取所有辅音。

                import pandas as pd
                import string
                
                df = pd.DataFrame(['Cat', 'DOG', 'bike', 'APPLE', 'foo bar'], columns=['words'])
                
                vowels = 'aeiouAEIOU'
                cons = ''.join(set(string.ascii_letters).difference(set(vowels)))
                trans = str.maketrans(vowels+cons, 'v'*len(vowels)+'c'*len(cons))
                

                df['translated'] = df['words'].str.translate(trans)
                
                     words translated
                0      Cat        cvc
                1      DOG        cvc
                2     bike       cvcv
                3    APPLE      vcccv
                4  foo bar    cvv cvc
                

                正是为此而设计的,所以速度很快。

                # Supporting code
                import perfplot
                import pandas as pd
                import string
                
                def with_translate(s):
                    vowels = 'aeiouAEIOU'
                    cons = ''.join(set(string.ascii_letters).difference(set(vowels)))
                    trans = str.maketrans(vowels+cons, 'v'*len(vowels)+'c'*len(cons))
                
                    return s.str.translate(trans)
                
                
                def with_replace(s):
                    return s.replace({"[^aeiouAEIOU]":'c', '[aeiouAEIOU]':'v'}, regex=True)
                
                
                perfplot.show(
                    setup=lambda n: pd.Series(np.random.choice(['foo', 'bAR', 'foobar', 'APPLE', 'ThisIsABigWord'], n)), 
                    kernels=[
                        lambda s: with_translate(s),
                        lambda s: with_replace(s),
                    ],
                    labels=['Translate', 'Replace'],
                    n_range=[2 ** k for k in range(19)],
                    equality_check=None,  
                    xlabel='len(s)'
                )
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2017-10-21
                  • 2023-03-22
                  • 2020-07-15
                  • 1970-01-01
                  • 2018-11-16
                  • 2021-10-10
                  • 2017-08-02
                  • 1970-01-01
                  相关资源
                  最近更新 更多