【发布时间】:2017-07-04 11:07:09
【问题描述】:
我是 python 新手,这是我的问题: 打开文件 romeo.txt 并逐行读取。对于每一行,使用 split() 方法将该行拆分为一个单词列表。该程序应该建立一个单词列表。对于每行上的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对生成的单词进行排序和打印。
这是文件:
但是透过窗外的光线会变得柔和
这是东方,朱丽叶是太阳
升起美丽的太阳,杀死嫉妒的月亮
谁已经病入膏肓了
期望的输出:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', '羡慕', 'fair', 'grief '、'是'、'杀'、'光'、'月'、'苍白'、'病'、'软'、'太阳'、'之'、'透'、'什么'、'窗'、 '与','那边']
这是我的代码:
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
#loop through the text to get the lines
for line in fh:
line = line.rstrip()
#loop through the line to get the words
for word in line:
words = line.split()
#if a word is not in the empty list, append it
if not word in lst: lst.append(word)
lst.sort()
print lst
我的输出:
['', 'A', 'B', 'I', 'J', 'W', 'a', 'b', 'c', 'd', 'e', 'f' ,'g','h','i','k','l','m','n','o','p','r','s','t',' u', 'v', 'w', 'y']
如果您能告诉我出了什么问题(只获取开头有空格的单词的第一个字母而不是整个单词),那就太好了..
注意:我希望代码使用这些指令,而不是其他高级指令(以保持我的学习顺序)
谢谢
【问题讨论】:
-
当您编写
for word in line:时,Python 将遍历它认为字符串line的“元素”:也就是说,它将逐个字符地遍历字符串。所以word总是一个字符。 (请注意,这里有一些混淆:你定义了words,但从不使用它。)
标签: python