Python:将文件中的单词加载到一个集合中 [英] Python: load words from file into a set

查看:31
本文介绍了Python:将文件中的单词加载到一个集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数千个单词的简单文本文件,每个单词各占一行,例如

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

aardvark
hello
piper

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

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")

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

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

谢谢

推荐答案

字符串的 strip() 方法去除两端的空格.

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

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

这篇关于Python:将文件中的单词加载到一个集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆