执行以下操作的最佳方法是什么?示例文档 (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']
最佳答案
你的错误在于这两行:
for word in words:
if word not in words:
也许你的意思是:
for word in words:
if word not in lst:
不管它值多少钱,下面是我编写整个程序的方式:
import string
result = sorted(set(
word.strip(string.punctuation)
for line in open('hello.txt')
for word in line.split()))
print result
关于python - 打开一个文件,将每一行拆分成一个列表,然后针对每一行的每个单词检查该单词是否在列表中,如果不在列表中则将其附加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29359401/