python - 打开一个文件,将每一行拆分成一个列表,然后针对每一行的每个单词检查该单词是否在列表中,如果不在列表中则将其附加到列表中

标签 python python-3.x

执行以下操作的最佳方法是什么?示例文档 (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/

相关文章:

python - 在 Python 中的不同行上打印列表元素

python - 在请求库中,如何避免 "HttpConnectionPool is full, discarding connection"警告?

python - Spyder IDE 中的 Markdown

python - 从两个数组创建所有可能的组合

python-3.x - 在我的应用程序中使用数据表

python - 如何获取当前的python解释器路径

python - 带超时的异步子进程

python - 有没有人有使用诱变剂写入文件的好例子?

python - 错误 : (wheel). whl 不是此平台上支持的轮子

python - 在 drake 中模拟非线性执行器