Python,如何使程序排序标题词和普通词?

时间:2015-03-30 12:36:33

标签: python list

我需要写一个会要求随机句子的程序,例如:"这是一个句子。"

它将打印出来:

Title words: This, Sentence
Words: is, a 

我该如何编写这样的程序?我开始了,我尝试了开始和结束,但不确定我是否正确的方式。到目前为止,我有这个:

while True:
    sentence = ("Please enter a sentence:")
    if sentence.title() == True:


for i in range (len(tword)):
    print ("Title words: ", tword[i])
    print ("Words: ", words[i])

有人可以给我提示或提示吗?

4 个答案:

答案 0 :(得分:2)

您可以使用istitle方法

sentence = input("Please enter a sentence:")
words = []
title = []
for i in sentence.split():
    if i.istitle():
        title.append(i)
    else:
        words.append(i)

>>>print('title words:',",".join(title))
title words: This,Sentence

>>>print('words:',",".join(words))
words: is,a

答案 1 :(得分:1)

尝试这样:

>>> my_sentence = "Hello how are you, hello World"
>>> import re
>>> my_sentence = "Hello how are you, hello World"
>>> my_words = re.findall("\w+", my_sentence)     #This will find all words
>>> my_words
['Hello', 'how', 'are', 'you', 'hello', 'World']
>>> my_dict = {}
>>> for x in my_words:
...     if x[0].isupper():  # check for if words start with uppercase or not
...         my_dict['title'] = my_dict.get("title", []) + [x]
...     else:
...         my_dict['word'] = my_dict.get("word", []) + [x]
...
>>> my_dict
{'word': ['how', 'are', 'you', 'hello'], 'title': ['Hello', 'World']}

您的期望输出:

>>> print "Title: {}\nWord: {}".format(", ".join(my_dict['title']), ", ".join(my_dict['word']))
Title: Hello, World
Word: how, are, you, hello

答案 2 :(得分:0)

请尝试以下操作:

title_array = [word for word in sentence.split() if word.istitle()]

从其他符号中删除它,更准确地说,

title_array = [''.join([c for c in word if c.isalnum()]) for word in sentence.split() if word.istitle()]

使用正则表达式,

[''.join([c for c in word if c.isalnum()]) for word in re.split('\W+', sentence) if word.istitle()]

答案 3 :(得分:0)

这是我使用你对标题词的定义所使用的方法:

import re

sentence = "This is a Sentence."
titles, words = [], []
for word in re.findall("\w+", sentence):
    [words, titles][word[0].isupper()].append(word)

print("Title: {}\nWord: {}".format(", ".join(titles), ", ".join(words)))

输出:

Title: This, Sentence
Word: is, a