0

我正在为初学者开设 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!"

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

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

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

4

2 回答 2

1

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

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

印刷:

True
False

这里的例子

于 2016-10-08T17:07:28.743 回答
0

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

学习如何使用正则表达式对于初学者来说可能看起来令人生畏,但通过一些练习你会发现它们非常有用和高效。

#!/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
于 2016-10-08T20:26:40.553 回答