【问题标题】:Checking if input's characters match the ones given in Python检查输入的字符是否与 Python 中给出的字符匹配
【发布时间】:2016-10-08 17:02:47
【问题描述】:

我正在为初学者开设 Python 课程。 我们必须创建一个代码,将最多 6 个单词的输入转换为首字母缩写词。

在创建首字母缩写词之前,它必须检查单词是否只包含给定集合中的字符,但我不能只检查它是否在字母表中,因为我们使用的是具有特殊字符(õ、ä、ö)的本地字母表, ü)。

def main():

    nr_of_words_limit = 6
    chars = "abcdefghijklmnopqrstuvwõäöüxyz"

    def not_allowed_characters_check(text, chars):
        """This checks if all words in text only include characters from chars"""

    def acronym(text, chars, nr_of_words_limit): 
        """Creates acronym after checking for not allowed characters"""

所以,在这种情况下:

text = "Hello World!"

由于感叹号,它只会说文本包含不允许的字符。

如果文本中每个单词中的每个字母都匹配字符,我将如何比较呢?

感谢您的帮助,非常感谢。

【问题讨论】:

    标签: python acronym


    【解决方案1】:

    最简单的方法是使用set(word).issubset(alphabet) 检查单词中的字符集是否是字母表的子集。例如:

    alpha_set = set("best") 
    print set("test").issubset(alpha_set)
    print set("testa").issubset(alpha_set)
    

    打印:

    True
    False
    

    Example here

    【讨论】:

      【解决方案2】:

      您可以使用regular expressions 检查文本中的每个单词是否与特定模式匹配。您的情况的模式是单词中的所有字符都应该是字母表中的字母:大写 A-Z 以及小写 a-z (我从您的示例中假设)和字母õäöü)。

      学习如何使用正则表达式对于初学者来说可能看起来很艰巨,但通过一些练习,您会发现它们非常有用且高效。

      #!/usr/bin/env python
      # -*- coding: utf-8 -*- 
      
      import re
      
      def check_allowed_chars(text):
          """
          """
          pattern = re.compile('[a-zA-Zõäöü]+$')
          words = text.split()
          for word in words:
              if not pattern.match(word):
                  print('The text contains not allowed characters!')
                  return
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-02
        • 2010-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多