我是Python新手,我正在尝试编写一段完成任务的代码:
您可以在http://www.pythonlearn.com/code/romeo.txt下载示例数据
这就是我目前所拥有的:
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = open('romeo.txt')
newList = []
for line in fname:
words = line.rstrip().split()
print words
我知道我需要使用另一个for
循环来检查是否有任何丢失的单词,最后需要使用sort()
函数对它们进行排序。Python解释器给了我一个错误,告诉我必须使用append()
来添加丢失的单词(如果它们不存在的话)。
我已经用我的代码构建了以下列表:
['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks'] ← Mismatch
['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
['Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon']
['Who', 'is', 'already', 'sick', 'and', 'pale', 'with', 'grief']
但是输出应该是这样的:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks','east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick','soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
如何调整代码以生成输出?
重要提示: 对于每个想帮忙的人,请确保你能从我的代码中完成这个测试,因为这是一个任务,我们必须遵循课程的水平。谢谢
这是我对代码的更新:
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = open('romeo.txt')
newList = list()
for line in fname:
words = line.rstrip().split()
for i in words:
newList.append(i)
newList.sort()
print newList
['起来','但是','它','朱丽叶','谁','已经','和','和','休息','东方','嫉妒','公平','悲伤','是','是','是','杀死','光明','月亮','苍白','生病','柔软','太阳','太阳','透过','什么','窗户','与','那边']
但我有重复!这是为什么,如何避免?
目前没有回答
相关问题 更多 >
编程相关推荐