执行以下操作的最佳方法是什么?示例文档(hello.txt)包含以下内容:
>>> repr(hello.txt) #show object representations
Hello there! This is a sample text. \n Ten plus ten is twenty. \n Twenty times two is forty \n
>>> print(hello.txt)
Hello There. This is a sample text
Ten plus ten is twenty
Twenty times two is forty
待办事项: 打开一个文件,将每一行拆分成一个列表,然后检查每一行中的每个单词是否在列表中,如果没有,则将其追加到列表中
open_file = open('hello.txt')
lst = list() #create empty list
for line in open_file:
line = line.rstrip() #strip white space at the end of each line
words = line.split() #split string into a list of words
for word in words:
if word not in words:
#Missing code here; tried 'if word not in words', but then it produces a empty list
lst.append(word)
lst.sort()
print(lst)
以上代码的输出:
['Hello', 'Ten', 'There', 'This', 'Twenty', 'a', 'forty', 'is', 'is', 'is', 'plus', 'sample', 'ten', 'text', 'times', 'twenty', 'two']
“is”字符串出现3次,而它应该只出现一次。我一直在想如何编写代码来检查每一行上的每个单词,看看这个单词是否在列表中,如果不在列表中,就把它追加到列表中。。
所需输出:
['Hello', 'Ten', 'There', 'This', 'Twenty', 'a', 'forty', 'is', 'plus', 'sample', 'ten', 'text', 'times', 'twenty', 'two']
解决方案:
你的错误在于这两行:
也许你的意思是:
不管它值多少钱,下面是我将如何编写整个程序:
集合是唯一成员身份的理想选择。
hello.txt
的内容:代码:
结果:
你也可以修改你的代码,比如说
if word not in lst
,而不是if word not in words
,这样它就可以工作了。如果你想排序一个集合。。。好吧,集合是无序的,但是您可以用
sorted(result)
对输出进行排序。相关问题 更多 >
编程相关推荐