Python:将文件中的单词加载到集合中

发布于 2024-07-19 07:58:45 字数 366 浏览 3 评论 0原文

我有一个简单的文本文件,其中包含数千个单词,每个单词都在自己的行中,例如,

aardvark
hello
piper

我使用以下代码将单词加载到集合中(我需要单词列表来测试成员资格,因此集合是我选择的数据结构):

my_set = set(open('filename.txt'))

上面的代码生成一个包含以下条目的集合(每个单词后跟一个空格和换行符:

("aardvark \n", "hello \n", "piper \n")

将文件加载到集合中但去掉空格和 \n 的最简单方法是什么?

谢谢

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 the words into a set (I need the list of words to test membership, so set is the data structure I chose):

my_set = set(open('filename.txt'))

The above code produces a set with the following entries (each word is followed by a space and new-line character:

("aardvark \n", "hello \n", "piper \n")

What's the simplest way to load the file into a set but get rid of the space and \n?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

美煞众生 2024-07-26 07:58:46
my_set = set(map(str.strip, open('filename.txt')))
my_set = set(map(str.strip, open('filename.txt')))
守望孤独 2024-07-26 07:58:46

仅删除右侧空格。

set(map(str.rstrip, open('filename.txt')))

To remove only the right hand spaces.

set(map(str.rstrip, open('filename.txt')))
千と千尋 2024-07-26 07:58:46
with open("filename.txt") as f:
    s = set([line.rstrip('\n') for line in f])
with open("filename.txt") as f:
    s = set([line.rstrip('\n') for line in f])
凉月流沐 2024-07-26 07:58:46
with open("filename.txt") as f:
    mySet = map(str.rstrip, f)

如果你想在Python 2.5中使用它,你需要

from __future__ import with_statement
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
孤檠 2024-07-26 07:58:45

字符串的 strip() 方法删除两端的空格。

set(line.strip() for line in open('filename.txt'))

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

set(line.strip() for line in open('filename.txt'))
嘿哥们儿 2024-07-26 07:58:45

只需加载所有文件数据并将其拆分,它将处理每行一个单词或每行用空格分隔的多个单词,并且一次加载整个文件会更快,除非您的文件是 GB 的

words =  set(open('filename.txt').read().split())

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())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文