从文件加载单词并列出该单词

时间:2014-02-23 09:51:15

标签: python

我的想法是从目录中加载单词(包含A Words.txt- Z Words.txt)并将其复制到列表中。以下代码有效,但在每个单词的末尾添加了"\n"(例如["apple\n", "abort\n"]);任何人都可以建议一种解决方法吗?

from io import *
import string

def load_words(base_dir):
words = []
for i in string.uppercase:
    location = base_dir+"\\"+i+" Words.txt"
    with open(location, "rb+") as f:
        words += f.readlines()
return words

3 个答案:

答案 0 :(得分:1)

使用str.rstrip明确删除换行符:

def load_words(base_dir):
    words = []
    for i in string.uppercase:
        location = base_dir+"\\"+i+" Words.txt"
        with open(location, "rb+") as f:
            for line in f:                      # <---------
                words.append(line.rstrip())     # <---------
            # OR words.extend(line.rstrip() for line in f)
    return words

答案 1 :(得分:1)

更改

words += f.readlines()

到:

words += [x.strip() for x in f.readlines()]

strip()删除了尾随和前导空格字符。

答案 2 :(得分:0)

试试这个。希望它有所帮助。

from io import *
import string

def load_words(base_dir):
words = []
for i in string.uppercase:
    location = base_dir+"\\"+i+" Words.txt"
    with open(location, "rb+") as f:
        for i in f.readlines():
            words.append(i.strip())
return words