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

编程入门 行业动态 更新时间:2024-10-16 02:24:37
本文介绍了Python:将文件中的单词加载到一个集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 20:18:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1399441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   加载   文件   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!