【发布时间】:2017-08-08 18:58:43
【问题描述】:
我在学习在线 Python 3(Coursera。爱他们)时遇到了困难。
我有一个包含几行的.txt 文件。每行都有几个单词。我需要将文件拆分为行,我已经在使用:
for line in fh:
line = line.rstrip()
line.split()
现在我需要按字母顺序对整个文件(从所有行)中的单词进行排序,但我得到的是列表中的字符串(我已经创建了名为 lst 的字符串)。因此,我将整个字符串按字母顺序排序,但无法对其中的单词进行排序。
我看到这个问题似乎已经被问过了,但有点不同。让我们以这段文字为例:
"In the beginning of creation of the heavens and the earth
Now the earth was astonishingly empty and darkness was"
我需要的是按字母顺序对整个单词列表进行排序(在修剪相同的单词之后),所以结果应该是['In', 'Now', 'and', 'astonishingly', 'beginning'] 等等。
我真的很努力地寻找自己,并且我正在认真学习这门课程。我需要一些帮助。
提前谢谢你,
【问题讨论】:
-
欢迎来到 SO。通常你应该包括一些示例数据和你解决问题的尝试。请阅读How to Ask和minimal reproducible example
-
在顶部创建一个空列表
all_words = [],对于每个line,您可以在末尾all_words.extend(line.rstrip().split())和all_words.sort()。 -
不需要所有迭代,因为没有任何参数的
str.split()会在 any 空格上拆分,并将连续的空格视为单个分隔符。所以"a b\t\tc\nd e f\n \ng".split()返回['a', 'b', 'c', 'd', 'e', 'f', 'g']。所以只需执行words = fh.read().split()然后words.sort()。 -
您想要唯一的词还是所有词?大小写重要吗?
"Now"和"now"一样吗?"James"和"james"呢?您的文本是否包含您需要忽略的标点符号?在"Python 3"中同时包含"Python"和"3"字词?
标签: python string python-3.x list sorting