[英]I am trying to read, append and sort all words in a file using Python in TextWrangler application.
Question : Open the file romeo.txt and read it line by line.问题:打开文件 romeo.txt 并逐行阅读。 For each line, split the line into a list of words using the split() method.对于每一行,使用 split() 方法将该行拆分为单词列表。 The program should build a list of words.该程序应该建立一个单词列表。 For each word on each line check to see if the word is already in the list and if not append it to the list.对于每行上的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。 When the program completes, sort and print the resulting words in alphabetical order.程序完成后,按字母顺序对结果单词进行排序和打印。
fname = raw_input('Enter the file name: ')
file = open(fname)
romeo = list()
for line in file:
words = line.split()
for current_word in words :
if current_word in romeo:
continue
romeo.append(current_word)
print romeo.sort()
I am getting an output of "None".我得到“无”的输出。 I am not sure what I am doing wrong This link is where the romeo.txt file is found.我不确定我做错了什么此链接是找到 romeo.txt 文件的位置。
The reason why you are getting None
is because romeo.sort()
does the sorting in place, so it actually returns nothing.你得到None
的原因是因为romeo.sort()
进行了适当的排序,所以它实际上什么都不返回。 You have to actually just print romeo
after you call romeo.sort()
.实际上,您必须在调用romeo.sort()
后才打印romeo
。
So, instead of printing romeo.sort()
, just print:因此,不要打印romeo.sort()
,只需打印:
print(romeo)
Without continue :没有继续:
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
word = line.split()
for item in word:
if item not in lst:
lst.append(item)
lst.sort()
print(lst)
fname = input("Enter file name: ") fname = input("请输入文件名:")
fh = open(fname) fh = 打开(fname)
lst = list() lst = 列表()
for line in fh:对于 fh 中的行:
x=line.split()
for word in x:
if word not in lst:
lst.append(word)
lst.sort()
print(lst)打印(lst)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.