Python 为什么我得不到文字,只有字母?

Python 为什么我得不到文字,只有字母?,python,Python,我想读一个用户通过输入选择的文件,并按字母顺序排列该txt文件中的所有单词。此特定代码的输出仅输出txt文件中的所有字母 输出示例: A. A. E L N p 所需输出:['apple','ein','pear','purple'] 如果你做了排序(单词),那么排序将你的单词(字符串)拆分成字母并进行排序,你不需要使用排序,只要使用排序后的单词就可以了,因为你的单词已经排序了!更正代码如下: 输入文件: apple purple pear ein apple purple pear

我想读一个用户通过输入选择的文件,并按字母顺序排列该txt文件中的所有单词。此特定代码的输出仅输出txt文件中的所有字母

  • 输出示例: A. A. E L N p

  • 所需输出:
    ['apple','ein','pear','purple']

如果你做了排序(单词),那么
排序
将你的单词(字符串)拆分成字母并进行排序,你不需要使用排序,只要使用排序后的单词就可以了,因为你的单词已经排序了!更正代码如下:

输入文件:

apple purple pear ein
apple purple pear ein
输出:

apple
ein
pear
purple
['apple', 'ein', 'pear', 'purple']
如果您需要在输出中有一个
列表
,您可以使用下一个简单代码:

输入文件:

apple purple pear ein
apple purple pear ein
输出:

apple
ein
pear
purple
['apple', 'ein', 'pear', 'purple']

你真的很接近!你只是不想在打印之前对单词进行排序。您已经对列表进行了排序:

f = open(input("What file would you like to import?"))
for word in sorted(f.read().split()):
    print(word)
示例文件内容:

now is the time for all good
men to come to the aid of
their country
结果:

aid
all
come
country
for
good
is
men
now
of
the
the
their
time
to
to

摆脱对sort()的第二次调用您认为排序(words)有什么作用?你为什么这么做?您之前已经在该行对列表进行了排序。您想要的输出根本没有排序。我可以删除冗余的.split调用,列表现在以aplha显示单词,但我现在需要将它们小写。非常感谢。只需用
word
替换
sorted(word)
。这不符合OPs代码的要求。@Steve更正!