我的想法是从目录中加载单词(包含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
答案 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)
答案 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