我正在尝试编写一个执行以下操作的函数
- 打开文件 word_list.txt
- 将这个文件的内容读入列表
- 按字母顺序排列列表
- 将列表的内容写入一个名为alphabetic.txt的文件
这是我的代码
def alphabetic():
file = open("word-text.txt","r")
data=file.read()
print (data)
file.close()
listsort=data
listsort.sort()
print(listsort)
每当我尝试运行这段代码时,我使用"file"的列表不会被排序,我得到以下结果(这与我的列表顺序相同),我试图用字母顺序对它们进行排序订单出错
>>> alphabetic()
apples
oranges
watermelon
kiwi
zucchini
carrot
okra
jalapeno
pepper
cucumber
banana
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
alphabetic()
File "/Users/user/Desk`enter code here`top/Outlook(1)/lab6.py", line 15, in alphabetic
listsort.sort()
AttributeError: 'str' object has no attribute 'sort'`
请您参考如下方法:
您的方法无效,因为 read 方法仅返回一个字符串。由于 Python 字符串没有 sort() 方法,因此您得到了您所犯的错误。 sort 方法适用于 lists,如我使用 readlines 方法所示。
如果这是您文件的内容:
apples
oranges
watermelon
kiwi
zucchini
carrot
okra
jalapeno
pepper
cucumber
banana
相关代码如下:
with open('word-text.txt', 'r') as f:
words = f.readlines()
#Strip the words of the newline characters (you may or may not want to do this):
words = [word.strip() for word in words]
#sort the list:
words.sort()
print words
这个输出:
['apples', 'banana', 'carrot', 'cucumber', 'jalapeno', 'kiwi', 'okra', 'oranges', 'pepper', 'watermelon', 'zucchini']
