Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 在python中按字母顺序列出文件中的单词_Python 2.7 - Fatal编程技术网

Python 2.7 在python中按字母顺序列出文件中的单词

Python 2.7 在python中按字母顺序列出文件中的单词,python-2.7,Python 2.7,我刚刚开始学习python。我必须完成的一项任务是编写一个代码,它将接收用户提交的文本文件,并按字母顺序列出文件中的单词 我的密码 f=open(raw_input("What file would you like to import?")) for word in f: print(sorted(word)) 这不是按字母顺序列出单词,而是按字母顺序列出单词中的字母 例如,输出的是['\n',a',h',m',n',u'],而不是人 编辑 文本文件中的单词位于单独的行上,如: hu

我刚刚开始学习python。我必须完成的一项任务是编写一个代码,它将接收用户提交的文本文件,并按字母顺序列出文件中的单词

我的密码

f=open(raw_input("What file would you like to import?"))
for word in f:
    print(sorted(word))
这不是按字母顺序列出单词,而是按字母顺序列出单词中的字母

例如,输出的是
['\n',a',h',m',n',u']
,而不是人

编辑

文本文件中的单词位于单独的行上,如:

human  
dog  
cat 
etc..
输出如下所示:

['\n', 'a', 'h', 'm', 'n', 'u']
['\n', 'd', 'g', 'o']
etc..
但是,我需要输出为: 土豚 猫 奶牛 狗
ect…

您的方法的问题是
for word in f
在文件中的行上循环,如果每行有一个单词,那么
排序(单词)
将仅对该单词的元素(字母)排序

相反,只需执行排序(f)即可对文件中的行(即单词)进行排序


请注意,这将包括行尾字符。使用
sorted(map(str.strip,f))
strip
函数应用于每一行/每一个字,以删除该属性。或者,您也可以使用
排序(f.read().split())
在任何空白字符处去除文件内容。当每行有多个单词时,这也会起作用。

更多信息会很好,比如单词是用空格还是换行的?谢谢,这正是我需要的。