[英]load words from file and make a list of that
My idea is to load words from a directory (contains A Words.txt- Z Words.txt) and copy it into a list. 我的想法是从目录中加载单词(包含A Words.txt- Z Words.txt)并将其复制到列表中。 The below code works, but adds
"\\n"
at the end of each word (example ["apple\\n", "abort\\n"]
); 下面的代码有效,但在每个单词的末尾添加
"\\n"
(例如["apple\\n", "abort\\n"]
); can anybody suggest a way to fix it? 任何人都可以建议一种解决方法吗?
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
Explicitly strip newlines using str.rstrip
: 使用
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
Try this. 尝试这个。 Hope it helps.
希望能帮助到你。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.