如何在Python中分隔大写和小写的单词?

时间:2014-04-08 22:08:55

标签: python python-2.7

我需要将至少包含一个大写字母的单词与小写分开。我需要输入输入并分隔大写单词和小写单词并将它们打印出来。这是我的代码:

text = input("Input your text: ")
words0 = text.strip().split()
words1 = []
words2 = []
wordslen= len(words0)
for word in words0:
    counter = 0
    for x in word:
        while counter != wordslen:
            if x.isupper():
                words1.append(word)
            else:
                words2.append(word)
            counter += 1
wordsupper = list(set(words1))
wordslower = list(set(words2))
allwords = wordsupper + wordslower

for word in allwords:
    print(word)

5 个答案:

答案 0 :(得分:1)

words = input("Input your text: ").strip().split()

lower, mixed = set(), set()
for word in words:
    if word == word.lower():
        lower.add(word)
    else:
        mixed.add(word)

print("Lowercase words: " + ", ".join(lower))
print("Mixed- and uppercase words: " + ", ".join(mixed))

的运行方式如下:

Input your text: This is a Perl and Python party.
Lowercase words: a, and, is, party.
Mixed- and uppercase words: This, Python, Perl

答案 1 :(得分:1)

这与以前的帖子类似,但使用map()代替for word in words:

text = raw_input("Input your text: ")
words = text.strip().split()

upper = []
lower = []
def sort_word(word):
    if word.lower() == word:
        lower.append(word)
    else:
        upper.append(word)

map(sort_word, words)

答案 2 :(得分:1)

要将仅包含小写字符的单词与其余单词分开:

text = raw_input('Input text: ')

lower, rest = set(), set()
for word in text.split():
    (lower if word == word.lower() else rest).add(word)
print(lower)
print(rest)

答案 3 :(得分:0)

也许是这样的:

text = input("Input your text: ")
words = text.strip().split()
wordslower = []
wordsupper = []

for word in words:
    # if the word is the same as word.lower() that means all the
    # characters are lower case.  Also, don't add duplicates to
    # the list.
    if word == word.lower():
        if word not in wordslower:
            wordslower.append(word)
    else: # The word has at least one capital letter
        if word not in wordsupper:
            wordsupper.append(word)

print(wordslower)
print(wordsupper)

答案 4 :(得分:0)

试试这个:

def check(word):
    for k in word:
        if k != k.lower(): #If the letter is capitalized
            return True
    return False

text = input('Text: ')
text = text.strip().split()

wordsupper = []
wordslower = []

for k in text:
    if check(k) == True:
        wordsupper.append(k)
    else:
        wordslower.append(k)

print(wordslower)
print(wordsupper)