简体   繁体   English

用Python分割句子

[英]Splitting Sentences in Python

Please input string: Python and Perl are programming languages 请输入字符串:Python和Perl是编程语言

Python
Perl
and
are 
programming
languages

I want an input to be split but the upper case words go on top. 我希望输入被拆分,但大写单词排在最前面。 I am thinking of using two lists: one with the title case words and one with lower. 我正在考虑使用两个列表:一个带有标题大小写单词,另一个带有较低的单词。 I am trying to use an if statement to place the words in a certain list. 我正在尝试使用if语句将单词放置在某个列表中。 Please suggest some ideas! 请提出一些建议!

Thanks 谢谢

Your example output is wrong, because it would look like this: 您的示例输出错误,因为它看起来像这样:

Perl
Python
and
are
languages
programming

Sorting by capital first would result in Perl above Python because e comes first. 首先按大写字母排序将使Perl高于Python因为e优先。 Additionally, because uppercase comes first you can simply do 此外,因为大写优先,所以您只需

print "\n".join(sorted(a.split()))

to get the desired result. 获得理想的结果。

EDIT: After rereading the question I came up with this fix/output: 编辑:重新阅读问题后,我想出了此修复程序/输出:

print "\n".join(sorted(a.split(), key=lambda x: x >= 'a'))

Output: 输出:

Python
Perl
and
are
programming
languages

Explanation: sorting functions in Python are stable , which means the order of elements is preserved relative to each other if they have the same comparison key. 说明: Python中的排序功能是稳定的 ,这意味着如果元素具有相同的比较键,则它们之间的顺序将相对保留。 The key function will assign a value of True to anything that is greater or equal to 'a' (which is any string starting with a lowercase letter), else False . 键函数将为大于或等于'a'任何值(这是任何以小写字母开头的字符串)分配True值,否则为False False compares smaller than True , so anything uppercase is moved to front, without changing the order of uppercase or lowercase words. False小于True ,因此任何大写字母都移到最前面,而不会更改大写或小写单词的顺序。

If it is a homework, you should give it a tag "homework". 如果是家庭作业,则应给它加上“家庭作业”标签。 Anyway, the idea to use two lists is not bad. 无论如何,使用两个列表的想法还不错。

  1. Initialize the two lists to empty ones. 将两个列表初始化为空列表。
  2. Split the input sentence using the .split() method of the string to get the words. 使用字符串的.split()方法拆分输入语句以获取单词。
  3. Use the split expression directly in the for loop to process the extracted words. 直接在for循环中使用split表达式来处理提取的单词。
  4. If word is the string variable, then word[0] is its first character. 如果word是字符串变量,则word[0]是其第一个字符。 If it is less or equal to 'Z' it is a capitalized word and should be appended to the wanted list. 如果小于或等于'Z' ,则为大写单词,应将其附加到所需列表之后。
  5. Use '\\n'.join(lst) to get the multiline string out of the list of words. 使用'\\n'.join(lst)从单词列表中获取多行字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM