开发者

Is there a shorter way to remove line breaks when reading from a file to a list?

Here is my current code:

dfile = open('dictionary.txt', 'r')
sfile = open('substrings.txt', 'r')
dictionary_words = []
开发者_如何学JAVAsubstrings = []

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?


Try this:

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


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]


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]


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')]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜