检查输入的字符是否与Python中给定的字符匹配

2024-04-29 08:13:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在上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"""

所以,在这种情况下:

^{pr2}$

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

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

谢谢你的帮助,真的很感激。在


Tags: oftextdef字母not字符单词nr
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

{cd1>中最简单的字符集}是检查字符集^的最简单方式。例如:

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

印刷品:

^{pr2}$

Example here

相关问题 更多 >