Python: load words from file into a set

后端 未结 6 1940
暗喜
暗喜 2020-12-29 20:14

I have a simple text file with several thousands of words, each in its own line, e.g.

aardvark
hello
piper

I use the following code to load

相关标签:
6条回答
  • 2020-12-29 20:54

    Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs

    words =  set(open('filename.txt').read().split())
    
    0 讨论(0)
  • 2020-12-29 21:03

    The strip() method of strings removes whitespace from both ends.

    set(line.strip() for line in open('filename.txt'))
    
    0 讨论(0)
  • 2020-12-29 21:08
    my_set = set(map(str.strip, open('filename.txt')))
    
    0 讨论(0)
  • 2020-12-29 21:10
    with open("filename.txt") as f:
        s = set([line.rstrip('\n') for line in f])
    
    0 讨论(0)
  • 2020-12-29 21:17
    with open("filename.txt") as f:
        mySet = map(str.rstrip, f)
    

    If you want to use this in Python 2.5, you need

    from __future__ import with_statement
    
    0 讨论(0)
  • 2020-12-29 21:18

    To remove only the right hand spaces.

    set(map(str.rstrip, open('filename.txt')))
    
    0 讨论(0)
提交回复
热议问题