【问题标题】:sort a .txt file after splitting the file to lines in Python 3在 Python 3 中将文件拆分为行后对 .txt 文件进行排序
【发布时间】: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 Askminimal 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


【解决方案1】:

如果你想要的只是文件中所有唯一单词的列表,并假设没有标点符号或其他非单词内容

word_list = sorted({ w for line in fh for w in line.strip().split() })

会做的

如果你想逐行排序的话

words = [ sorted(set(line.strip().split())) for line in fh ]

会这样做

【讨论】:

  • line.strip().split() 将始终等于 line.split()。但是为什么不更直接地使用word_list = sorted(fh.read().split())
  • 谢谢!虽然我们没有在 sorted() 函数上工作,但它仍然有效,但有点不同。感谢您的时间和帮助。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
相关资源
最近更新 更多