如何确定一个单词是否按字母顺序在 Python 中拼写 [英] How to figure out if a word in spelled in alphabetical order in Python

查看:51
本文介绍了如何确定一个单词是否按字母顺序在 Python 中拼写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个充满文字的文本文件.我需要浏览文本文件并计算按字母顺序拼写的单词数.我正在努力想办法弄清楚一个词是否按字母顺序排列.

我已经环顾四周,发现可以通过 sorted 来完成.但是,我们还没有在课堂上学习排序,所以我不能使用它.非常感谢帮助/提示.

我是否需要为字母表中的每个字母分配一个数字?

解决方案

信不信由你,所有字符都已经隐式分配了一个数字:它们的 ASCII 字符代码.您可以使用 ord() 函数访问它们,或者直接比较它们:

<预><代码>>>>一个">乙"错误的>>>b">一种"真的

但请注意,大写字母编码为 65 - 90,而小写字母编码为 97 - 122,因此:

<预><代码>>>>C">乙"错误的

您必须确保比较所有大写字母或所有小写字母.

这是一个可能的函数,它使用上述信息来检查给定的字符串是否按字母顺序排列,只是为了让您开始:

def isAlphabetical(word):对于 xrange(len(word) - 1) 中的 i:如果单词[i] >字[i+1]:返回错误返回真

I have a text file full of words. I need to go through the text file and count the number of words that are spelled in alphabetical order. I am struggling to think of way to figure out if a word is in alphabetical order.

I have already looked around and have seen that it can be done with sorted. However, we haven't yet learned about sort in class so I can't use it. Help/tips much appreciated.

Do I need to do something like assigning each letter of the alphabet a number?

解决方案

Believe it or not, all characters are already implicitly assigned a number: their ASCII character codes. You can access them by using the ord() function, or compare them directly:

>>> "a" > "b"
False

>>> "b" > "a"
True

Beware though, capital letters are coded 65 - 90, while lowercase letters are coded 97 - 122, so:

>>> "C" > "b"
False

You have to ensure that you are comparing all uppercase or all lowercase letters.

Here's one possible function that uses the above information to check if a given string is in alphabetical order, just to get you started:

def isAlphabetical(word):
    for i in xrange(len(word) - 1):
        if word[i] > word[i+1]:
            return False
    return True

这篇关于如何确定一个单词是否按字母顺序在 Python 中拼写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆