从文件读取到列表时是否有更短的方法来删除换行符?

发布于 2024-12-08 23:40:28 字数 339 浏览 1 评论 0 原文

这是我当前的代码:

dfile = open('dictionary.txt', 'r')
sfile = open('substrings.txt', 'r')
dictionary_words = []
substrings = []

for line in dfile:
    dictionary_words.append(line.rstrip('\n'))
for line in sfile:
    substrings.append(line.rstrip('\n'))

它可以工作,但看起来很冗长。

这是写出此内容的适当方法,还是我错过了一个更简单的过程?

Here is my current code:

dfile = open('dictionary.txt', 'r')
sfile = open('substrings.txt', 'r')
dictionary_words = []
substrings = []

for line in dfile:
    dictionary_words.append(line.rstrip('\n'))
for line in sfile:
    substrings.append(line.rstrip('\n'))

It works but seems pretty wordy.

Is this the appropriate way to write this out, or am I missing a simpler process?

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

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

发布评论

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

评论(5

鲸落 2024-12-15 23:40:28

试试这个:

with open('dictionary.txt', 'r') as f:
    dictionary_words = f.read().splitlines()

Try this:

with open('dictionary.txt', 'r') as f:
    dictionary_words = f.read().splitlines()
小矜持 2024-12-15 23:40:28

使用 map

dictionary_words = map(lambda line: line.rstrip('\n'), dfile)

列表理解

dictionary_words = [line.rstrip('\n') for line in dfile]

Either use map:

dictionary_words = map(lambda line: line.rstrip('\n'), dfile)

or a list comprehension:

dictionary_words = [line.rstrip('\n') for line in dfile]
茶色山野 2024-12-15 23:40:28

一个稍微简洁的替代方案是使用列表推导式:

with open('dictionary.txt', 'r') as dfile:
  dictionary_words = [line.rstrip('\n') for line in dfile]

with open('substrings.txt', 'r') as sfile:
  substrings  = [line.rstrip('\n') for line in sfile]

A slightly less wordy alternative is to use list comprehensions:

with open('dictionary.txt', 'r') as dfile:
  dictionary_words = [line.rstrip('\n') for line in dfile]

with open('substrings.txt', 'r') as sfile:
  substrings  = [line.rstrip('\n') for line in sfile]
仲春光 2024-12-15 23:40:28

看来你的字典文件一行中有一个单词。它可能会帮助你:

>>> words = [w.strip() for w in open('dictionary.txt').read().split('\n')]

It seems your dictionary file has one word at line. It may help you:

>>> words = [w.strip() for w in open('dictionary.txt').read().split('\n')]
清音悠歌 2024-12-15 23:40:28

正如 @Chris 在评论中提到的,你可以定义一个函数:

def words_fromfile(filename):
    with open(filename) as f:
         return f.read().splitlines()

dictionary_words = words_fromfile('dictionary.txt')
substrings = words_fromfile('substrings.txt')

如果你出于某种原因不喜欢它,你可以稍后更改函数定义,而无需触及代码的其余部分。

As @Chris mentions in the comment you could define a function:

def words_fromfile(filename):
    with open(filename) as f:
         return f.read().splitlines()

dictionary_words = words_fromfile('dictionary.txt')
substrings = words_fromfile('substrings.txt')

You could always change the function definition later if you don't like it for some reason without touching the rest of the code.

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